]> git.lizzy.rs Git - rust.git/blob - src/librand/distributions/normal.rs
cc70a695c8d594c1ab85cac67006c7a1ad77cd5c
[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 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x }
60         }
61
62         StandardNormal(ziggurat(
63             rng,
64             true, // this is symmetric
65             &ziggurat_tables::ZIG_NORM_X,
66             &ziggurat_tables::ZIG_NORM_F,
67             pdf, zero_case))
68     }
69 }
70
71 /// The normal distribution `N(mean, std_dev**2)`.
72 ///
73 /// This uses the ZIGNOR variant of the Ziggurat method, see
74 /// `StandardNormal` for more details.
75 #[derive(Copy, Clone)]
76 pub struct Normal {
77     mean: f64,
78     std_dev: f64,
79 }
80
81 impl Normal {
82     /// Construct a new `Normal` distribution with the given mean and
83     /// standard deviation.
84     ///
85     /// # Panics
86     ///
87     /// Panics if `std_dev < 0`.
88     pub fn new(mean: f64, std_dev: f64) -> Normal {
89         assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
90         Normal {
91             mean: mean,
92             std_dev: std_dev
93         }
94     }
95 }
96 impl Sample<f64> for Normal {
97     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
98 }
99 impl IndependentSample<f64> for Normal {
100     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
101         let StandardNormal(n) = rng.gen::<StandardNormal>();
102         self.mean + self.std_dev * n
103     }
104 }
105
106
107 /// The log-normal distribution `ln N(mean, std_dev**2)`.
108 ///
109 /// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
110 /// std_dev**2)` distributed.
111 #[derive(Copy, Clone)]
112 pub struct LogNormal {
113     norm: Normal
114 }
115
116 impl LogNormal {
117     /// Construct a new `LogNormal` distribution with the given mean
118     /// and standard deviation.
119     ///
120     /// # Panics
121     ///
122     /// Panics if `std_dev < 0`.
123     pub fn new(mean: f64, std_dev: f64) -> LogNormal {
124         assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
125         LogNormal { norm: Normal::new(mean, std_dev) }
126     }
127 }
128 impl Sample<f64> for LogNormal {
129     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
130 }
131 impl IndependentSample<f64> for LogNormal {
132     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
133         self.norm.ind_sample(rng).exp()
134     }
135 }
136
137 #[cfg(test)]
138 mod tests {
139     use std::prelude::v1::*;
140
141     use distributions::{Sample, IndependentSample};
142     use super::{Normal, LogNormal};
143
144     #[test]
145     fn test_normal() {
146         let mut norm = Normal::new(10.0, 10.0);
147         let mut rng = ::test::rng();
148         for _ in 0..1000 {
149             norm.sample(&mut rng);
150             norm.ind_sample(&mut rng);
151         }
152     }
153     #[test]
154     #[should_panic]
155     fn test_normal_invalid_sd() {
156         Normal::new(10.0, -1.0);
157     }
158
159
160     #[test]
161     fn test_log_normal() {
162         let mut lnorm = LogNormal::new(10.0, 10.0);
163         let mut rng = ::test::rng();
164         for _ in 0..1000 {
165             lnorm.sample(&mut rng);
166             lnorm.ind_sample(&mut rng);
167         }
168     }
169     #[test]
170     #[should_panic]
171     fn test_log_normal_invalid_sd() {
172         LogNormal::new(10.0, -1.0);
173     }
174 }
175
176 #[cfg(test)]
177 mod bench {
178     extern crate test;
179     use std::prelude::v1::*;
180     use self::test::Bencher;
181     use std::mem::size_of;
182     use distributions::{Sample};
183     use super::Normal;
184
185     #[bench]
186     fn rand_normal(b: &mut Bencher) {
187         let mut rng = ::test::weak_rng();
188         let mut normal = Normal::new(-2.71828, 3.14159);
189
190         b.iter(|| {
191             for _ in 0..::RAND_BENCH_N {
192                 normal.sample(&mut rng);
193             }
194         });
195         b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
196     }
197 }