Skip to content

Commit a417dbd

Browse files
committed
auto merge of #10859 : huonw/rust/helper-dists, r=cmr
This moves `std::rand::distribitions::{Normal, StandardNormal}` to `...::distributions::normal`, reexporting `Normal` from `distributions` (and similarly for `Exp` and Exp1`), and adds: - Log-normal - Chi-squared - F - Student T all of which are implemented in C++11's random library. Tests in huonw/random-tests@0424b8a. Note that these are approximately half documentation & half implementation (of which a significant portion is boilerplate `}`'s and so on).
2 parents e5f2021 + 705b705 commit a417dbd

File tree

4 files changed

+568
-246
lines changed

4 files changed

+568
-246
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
//! The exponential distribution.
12+
13+
use rand::{Rng, Rand};
14+
use rand::distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
15+
16+
/// A wrapper around an `f64` to generate Exp(1) random numbers.
17+
///
18+
/// See `Exp` for the general exponential distribution.Note that this
19+
// has to be unwrapped before use as an `f64` (using either
20+
/// `*` or `cast::transmute` is safe).
21+
///
22+
/// Implemented via the ZIGNOR variant[1] of the Ziggurat method. The
23+
/// exact description in the paper was adjusted to use tables for the
24+
/// exponential distribution rather than normal.
25+
///
26+
/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
27+
/// Generate Normal Random
28+
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
29+
/// College, Oxford
30+
pub struct Exp1(f64);
31+
32+
// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
33+
impl Rand for Exp1 {
34+
#[inline]
35+
fn rand<R:Rng>(rng: &mut R) -> Exp1 {
36+
#[inline]
37+
fn pdf(x: f64) -> f64 {
38+
(-x).exp()
39+
}
40+
#[inline]
41+
fn zero_case<R:Rng>(rng: &mut R, _u: f64) -> f64 {
42+
ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln()
43+
}
44+
45+
Exp1(ziggurat(rng, false,
46+
&ziggurat_tables::ZIG_EXP_X,
47+
&ziggurat_tables::ZIG_EXP_F,
48+
pdf, zero_case))
49+
}
50+
}
51+
52+
/// The exponential distribution `Exp(lambda)`.
53+
///
54+
/// This distribution has density function: `f(x) = lambda *
55+
/// exp(-lambda * x)` for `x > 0`.
56+
///
57+
/// # Example
58+
///
59+
/// ```rust
60+
/// use std::rand;
61+
/// use std::rand::distributions::{Exp, IndependentSample};
62+
///
63+
/// fn main() {
64+
/// let exp = Exp::new(2.0);
65+
/// let v = exp.ind_sample(&mut rand::task_rng());
66+
/// println!("{} is from a Exp(2) distribution", v);
67+
/// }
68+
/// ```
69+
pub struct Exp {
70+
/// `lambda` stored as `1/lambda`, since this is what we scale by.
71+
priv lambda_inverse: f64
72+
}
73+
74+
impl Exp {
75+
/// Construct a new `Exp` with the given shape parameter
76+
/// `lambda`. Fails if `lambda <= 0`.
77+
pub fn new(lambda: f64) -> Exp {
78+
assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0");
79+
Exp { lambda_inverse: 1.0 / lambda }
80+
}
81+
}
82+
83+
impl Sample<f64> for Exp {
84+
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
85+
}
86+
impl IndependentSample<f64> for Exp {
87+
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
88+
(*rng.gen::<Exp1>()) * self.lambda_inverse
89+
}
90+
}
91+
92+
#[cfg(test)]
93+
mod test {
94+
use rand::*;
95+
use super::*;
96+
use iter::range;
97+
use option::{Some, None};
98+
99+
#[test]
100+
fn test_exp() {
101+
let mut exp = Exp::new(10.0);
102+
let mut rng = task_rng();
103+
for _ in range(0, 1000) {
104+
assert!(exp.sample(&mut rng) >= 0.0);
105+
assert!(exp.ind_sample(&mut rng) >= 0.0);
106+
}
107+
}
108+
#[test]
109+
#[should_fail]
110+
fn test_exp_invalid_lambda_zero() {
111+
Exp::new(0.0);
112+
}
113+
#[test]
114+
#[should_fail]
115+
fn test_exp_invalid_lambda_neg() {
116+
Exp::new(-10.0);
117+
}
118+
}
119+
120+
#[cfg(test)]
121+
mod bench {
122+
use extra::test::BenchHarness;
123+
use rand::{XorShiftRng, RAND_BENCH_N};
124+
use super::*;
125+
use iter::range;
126+
use option::{Some, None};
127+
use mem::size_of;
128+
129+
#[bench]
130+
fn rand_exp(bh: &mut BenchHarness) {
131+
let mut rng = XorShiftRng::new();
132+
let mut exp = Exp::new(2.71828 * 3.14159);
133+
134+
bh.iter(|| {
135+
for _ in range(0, RAND_BENCH_N) {
136+
exp.sample(&mut rng);
137+
}
138+
});
139+
bh.bytes = size_of::<f64>() as u64 * RAND_BENCH_N;
140+
}
141+
}

src/libstd/rand/distributions/gamma.rs

+210-2
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
//! The Gamma distribution.
11+
//! The Gamma and derived distributions.
1212
1313
use rand::{Rng, Open01};
14-
use super::{IndependentSample, Sample, StandardNormal, Exp};
14+
use super::{IndependentSample, Sample, Exp};
15+
use super::normal::StandardNormal;
1516
use num;
1617

1718
/// The Gamma distribution `Gamma(shape, scale)` distribution.
@@ -168,6 +169,213 @@ impl IndependentSample<f64> for GammaLargeShape {
168169
}
169170
}
170171

172+
/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of
173+
/// freedom.
174+
///
175+
/// For `k > 0` integral, this distribution is the sum of the squares
176+
/// of `k` independent standard normal random variables. For other
177+
/// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2,
178+
/// 2)`.
179+
///
180+
/// # Example
181+
///
182+
/// ```rust
183+
/// use std::rand;
184+
/// use std::rand::distributions::{ChiSquared, IndependentSample};
185+
///
186+
/// fn main() {
187+
/// let chi = ChiSquared::new(11.0);
188+
/// let v = chi.ind_sample(&mut rand::task_rng());
189+
/// println!("{} is from a χ²(11) distribution", v)
190+
/// }
191+
/// ```
192+
pub enum ChiSquared {
193+
// k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1,
194+
// e.g. when alpha = 1/2 as it would be for this case, so special-
195+
// casing and using the definition of N(0,1)^2 is faster.
196+
priv DoFExactlyOne,
197+
priv DoFAnythingElse(Gamma)
198+
}
199+
200+
impl ChiSquared {
201+
/// Create a new chi-squared distribution with degrees-of-freedom
202+
/// `k`. Fails if `k < 0`.
203+
pub fn new(k: f64) -> ChiSquared {
204+
if k == 1.0 {
205+
DoFExactlyOne
206+
} else {
207+
assert!(k > 0.0, "ChiSquared::new called with `k` < 0");
208+
DoFAnythingElse(Gamma::new(0.5 * k, 2.0))
209+
}
210+
}
211+
}
212+
impl Sample<f64> for ChiSquared {
213+
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
214+
}
215+
impl IndependentSample<f64> for ChiSquared {
216+
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
217+
match *self {
218+
DoFExactlyOne => {
219+
// k == 1 => N(0,1)^2
220+
let norm = *rng.gen::<StandardNormal>();
221+
norm * norm
222+
}
223+
DoFAnythingElse(ref g) => g.ind_sample(rng)
224+
}
225+
}
226+
}
227+
228+
/// The Fisher F distribution `F(m, n)`.
229+
///
230+
/// This distribution is equivalent to the ratio of two normalised
231+
/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) /
232+
/// (χ²(n)/n)`.
233+
///
234+
/// # Example
235+
///
236+
/// ```rust
237+
/// use std::rand;
238+
/// use std::rand::distributions::{FisherF, IndependentSample};
239+
///
240+
/// fn main() {
241+
/// let f = FisherF::new(2.0, 32.0);
242+
/// let v = f.ind_sample(&mut rand::task_rng());
243+
/// println!("{} is from an F(2, 32) distribution", v)
244+
/// }
245+
/// ```
246+
pub struct FisherF {
247+
priv numer: ChiSquared,
248+
priv denom: ChiSquared,
249+
// denom_dof / numer_dof so that this can just be a straight
250+
// multiplication, rather than a division.
251+
priv dof_ratio: f64,
252+
}
253+
254+
impl FisherF {
255+
/// Create a new `FisherF` distribution, with the given
256+
/// parameter. Fails if either `m` or `n` are not positive.
257+
pub fn new(m: f64, n: f64) -> FisherF {
258+
assert!(m > 0.0, "FisherF::new called with `m < 0`");
259+
assert!(n > 0.0, "FisherF::new called with `n < 0`");
260+
261+
FisherF {
262+
numer: ChiSquared::new(m),
263+
denom: ChiSquared::new(n),
264+
dof_ratio: n / m
265+
}
266+
}
267+
}
268+
impl Sample<f64> for FisherF {
269+
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
270+
}
271+
impl IndependentSample<f64> for FisherF {
272+
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
273+
self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio
274+
}
275+
}
276+
277+
/// The Student t distribution, `t(nu)`, where `nu` is the degrees of
278+
/// freedom.
279+
///
280+
/// # Example
281+
///
282+
/// ```rust
283+
/// use std::rand;
284+
/// use std::rand::distributions::{StudentT, IndependentSample};
285+
///
286+
/// fn main() {
287+
/// let t = StudentT::new(11.0);
288+
/// let v = t.ind_sample(&mut rand::task_rng());
289+
/// println!("{} is from a t(11) distribution", v)
290+
/// }
291+
/// ```
292+
pub struct StudentT {
293+
priv chi: ChiSquared,
294+
priv dof: f64
295+
}
296+
297+
impl StudentT {
298+
/// Create a new Student t distribution with `n` degrees of
299+
/// freedom. Fails if `n <= 0`.
300+
pub fn new(n: f64) -> StudentT {
301+
assert!(n > 0.0, "StudentT::new called with `n <= 0`");
302+
StudentT {
303+
chi: ChiSquared::new(n),
304+
dof: n
305+
}
306+
}
307+
}
308+
impl Sample<f64> for StudentT {
309+
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
310+
}
311+
impl IndependentSample<f64> for StudentT {
312+
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
313+
let norm = *rng.gen::<StandardNormal>();
314+
norm * (self.dof / self.chi.ind_sample(rng)).sqrt()
315+
}
316+
}
317+
318+
#[cfg(test)]
319+
mod test {
320+
use rand::*;
321+
use super::*;
322+
use iter::range;
323+
use option::{Some, None};
324+
325+
#[test]
326+
fn test_chi_squared_one() {
327+
let mut chi = ChiSquared::new(1.0);
328+
let mut rng = task_rng();
329+
for _ in range(0, 1000) {
330+
chi.sample(&mut rng);
331+
chi.ind_sample(&mut rng);
332+
}
333+
}
334+
#[test]
335+
fn test_chi_squared_small() {
336+
let mut chi = ChiSquared::new(0.5);
337+
let mut rng = task_rng();
338+
for _ in range(0, 1000) {
339+
chi.sample(&mut rng);
340+
chi.ind_sample(&mut rng);
341+
}
342+
}
343+
#[test]
344+
fn test_chi_squared_large() {
345+
let mut chi = ChiSquared::new(30.0);
346+
let mut rng = task_rng();
347+
for _ in range(0, 1000) {
348+
chi.sample(&mut rng);
349+
chi.ind_sample(&mut rng);
350+
}
351+
}
352+
#[test]
353+
#[should_fail]
354+
fn test_log_normal_invalid_dof() {
355+
ChiSquared::new(-1.0);
356+
}
357+
358+
#[test]
359+
fn test_f() {
360+
let mut f = FisherF::new(2.0, 32.0);
361+
let mut rng = task_rng();
362+
for _ in range(0, 1000) {
363+
f.sample(&mut rng);
364+
f.ind_sample(&mut rng);
365+
}
366+
}
367+
368+
#[test]
369+
fn test_t() {
370+
let mut t = StudentT::new(11.0);
371+
let mut rng = task_rng();
372+
for _ in range(0, 1000) {
373+
t.sample(&mut rng);
374+
t.ind_sample(&mut rng);
375+
}
376+
}
377+
}
378+
171379
#[cfg(test)]
172380
mod bench {
173381
use super::*;

0 commit comments

Comments
 (0)