]> git.lizzy.rs Git - rust.git/blob - src/librand/distributions/normal.rs
Only retain external static symbols across LTO
[rust.git] / src / librand / distributions / normal.rs
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 normal and derived distributions.
12
13 use FloatMath;
14
15 use {Rng, Rand, Open01};
16 use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
17
18 /// A wrapper around an `f64` to generate N(0, 1) random numbers
19 /// (a.k.a.  a standard normal, or Gaussian).
20 ///
21 /// See `Normal` for the general normal distribution. That this has to
22 /// be unwrapped before use as an `f64` (using either `*` or
23 /// `mem::transmute` is safe).
24 ///
25 /// Implemented via the ZIGNOR variant[1] of the Ziggurat method.
26 ///
27 /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
28 /// Generate Normal Random
29 /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
30 /// College, Oxford
31 #[derive(Copy, Clone)]
32 pub struct StandardNormal(pub f64);
33
34 impl Rand for StandardNormal {
35     fn rand<R: Rng>(rng: &mut R) -> StandardNormal {
36         #[inline]
37         fn pdf(x: f64) -> f64 {
38             (-x * x / 2.0).exp()
39         }
40         #[inline]
41         fn zero_case<R: Rng>(rng: &mut R, u: f64) -> f64 {
42             // compute a random number in the tail by hand
43
44             // strange initial conditions, because the loop is not
45             // do-while, so the condition should be true on the first
46             // run, they get overwritten anyway (0 < 1, so these are
47             // good).
48             let mut x = 1.0f64;
49             let mut y = 0.0f64;
50
51             while -2.0 * y < x * x {
52                 let Open01(x_) = rng.gen::<Open01<f64>>();
53                 let Open01(y_) = rng.gen::<Open01<f64>>();
54
55                 x = x_.ln() / ziggurat_tables::ZIG_NORM_R;
56                 y = y_.ln();
57             }
58
59             if u < 0.0 {
60                 x - ziggurat_tables::ZIG_NORM_R
61             } else {
62                 ziggurat_tables::ZIG_NORM_R - x
63             }
64         }
65
66         StandardNormal(ziggurat(rng,
67                                 true, // this is symmetric
68                                 &ziggurat_tables::ZIG_NORM_X,
69                                 &ziggurat_tables::ZIG_NORM_F,
70                                 pdf,
71                                 zero_case))
72     }
73 }
74
75 /// The normal distribution `N(mean, std_dev**2)`.
76 ///
77 /// This uses the ZIGNOR variant of the Ziggurat method, see
78 /// `StandardNormal` for more details.
79 #[derive(Copy, Clone)]
80 pub struct Normal {
81     mean: f64,
82     std_dev: f64,
83 }
84
85 impl Normal {
86     /// Construct a new `Normal` distribution with the given mean and
87     /// standard deviation.
88     ///
89     /// # Panics
90     ///
91     /// Panics if `std_dev < 0`.
92     pub fn new(mean: f64, std_dev: f64) -> Normal {
93         assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
94         Normal {
95             mean: mean,
96             std_dev: std_dev,
97         }
98     }
99 }
100 impl Sample<f64> for Normal {
101     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 {
102         self.ind_sample(rng)
103     }
104 }
105 impl IndependentSample<f64> for Normal {
106     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
107         let StandardNormal(n) = rng.gen::<StandardNormal>();
108         self.mean + self.std_dev * n
109     }
110 }
111
112
113 /// The log-normal distribution `ln N(mean, std_dev**2)`.
114 ///
115 /// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
116 /// std_dev**2)` distributed.
117 #[derive(Copy, Clone)]
118 pub struct LogNormal {
119     norm: Normal,
120 }
121
122 impl LogNormal {
123     /// Construct a new `LogNormal` distribution with the given mean
124     /// and standard deviation.
125     ///
126     /// # Panics
127     ///
128     /// Panics if `std_dev < 0`.
129     pub fn new(mean: f64, std_dev: f64) -> LogNormal {
130         assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
131         LogNormal { norm: Normal::new(mean, std_dev) }
132     }
133 }
134 impl Sample<f64> for LogNormal {
135     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 {
136         self.ind_sample(rng)
137     }
138 }
139 impl IndependentSample<f64> for LogNormal {
140     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
141         self.norm.ind_sample(rng).exp()
142     }
143 }
144
145 #[cfg(test)]
146 mod tests {
147     use distributions::{Sample, IndependentSample};
148     use super::{Normal, LogNormal};
149
150     #[test]
151     fn test_normal() {
152         let mut norm = Normal::new(10.0, 10.0);
153         let mut rng = ::test::rng();
154         for _ in 0..1000 {
155             norm.sample(&mut rng);
156             norm.ind_sample(&mut rng);
157         }
158     }
159     #[test]
160     #[should_panic]
161     fn test_normal_invalid_sd() {
162         Normal::new(10.0, -1.0);
163     }
164
165
166     #[test]
167     fn test_log_normal() {
168         let mut lnorm = LogNormal::new(10.0, 10.0);
169         let mut rng = ::test::rng();
170         for _ in 0..1000 {
171             lnorm.sample(&mut rng);
172             lnorm.ind_sample(&mut rng);
173         }
174     }
175     #[test]
176     #[should_panic]
177     fn test_log_normal_invalid_sd() {
178         LogNormal::new(10.0, -1.0);
179     }
180 }
181
182 #[cfg(test)]
183 mod bench {
184     extern crate test;
185     use self::test::Bencher;
186     use std::mem::size_of;
187     use distributions::Sample;
188     use super::Normal;
189
190     #[bench]
191     fn rand_normal(b: &mut Bencher) {
192         let mut rng = ::test::weak_rng();
193         let mut normal = Normal::new(-2.71828, 3.14159);
194
195         b.iter(|| {
196             for _ in 0..::RAND_BENCH_N {
197                 normal.sample(&mut rng);
198             }
199         });
200         b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
201     }
202 }