]> git.lizzy.rs Git - rust.git/blob - src/librand/distributions/normal.rs
Merge pull request #20510 from tshepang/patch-6
[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 core::num::Float;
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)]
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 ///
76 /// # Example
77 ///
78 /// ```rust
79 /// use std::rand;
80 /// use std::rand::distributions::{Normal, IndependentSample};
81 ///
82 /// // mean 2, standard deviation 3
83 /// let normal = Normal::new(2.0, 3.0);
84 /// let v = normal.ind_sample(&mut rand::thread_rng());
85 /// println!("{} is from a N(2, 9) distribution", v)
86 /// ```
87 #[derive(Copy)]
88 pub struct Normal {
89     mean: f64,
90     std_dev: f64,
91 }
92
93 impl Normal {
94     /// Construct a new `Normal` distribution with the given mean and
95     /// standard deviation.
96     ///
97     /// # Panics
98     ///
99     /// Panics if `std_dev < 0`.
100     pub fn new(mean: f64, std_dev: f64) -> Normal {
101         assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0");
102         Normal {
103             mean: mean,
104             std_dev: std_dev
105         }
106     }
107 }
108 impl Sample<f64> for Normal {
109     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
110 }
111 impl IndependentSample<f64> for Normal {
112     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
113         let StandardNormal(n) = rng.gen::<StandardNormal>();
114         self.mean + self.std_dev * n
115     }
116 }
117
118
119 /// The log-normal distribution `ln N(mean, std_dev**2)`.
120 ///
121 /// If `X` is log-normal distributed, then `ln(X)` is `N(mean,
122 /// std_dev**2)` distributed.
123 ///
124 /// # Example
125 ///
126 /// ```rust
127 /// use std::rand;
128 /// use std::rand::distributions::{LogNormal, IndependentSample};
129 ///
130 /// // mean 2, standard deviation 3
131 /// let log_normal = LogNormal::new(2.0, 3.0);
132 /// let v = log_normal.ind_sample(&mut rand::thread_rng());
133 /// println!("{} is from an ln N(2, 9) distribution", v)
134 /// ```
135 #[derive(Copy)]
136 pub struct LogNormal {
137     norm: Normal
138 }
139
140 impl LogNormal {
141     /// Construct a new `LogNormal` distribution with the given mean
142     /// and standard deviation.
143     ///
144     /// # Panics
145     ///
146     /// Panics if `std_dev < 0`.
147     pub fn new(mean: f64, std_dev: f64) -> LogNormal {
148         assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
149         LogNormal { norm: Normal::new(mean, std_dev) }
150     }
151 }
152 impl Sample<f64> for LogNormal {
153     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
154 }
155 impl IndependentSample<f64> for LogNormal {
156     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
157         self.norm.ind_sample(rng).exp()
158     }
159 }
160
161 #[cfg(test)]
162 mod tests {
163     use std::prelude::v1::*;
164
165     use distributions::{Sample, IndependentSample};
166     use super::{Normal, LogNormal};
167
168     #[test]
169     fn test_normal() {
170         let mut norm = Normal::new(10.0, 10.0);
171         let mut rng = ::test::rng();
172         for _ in range(0u, 1000) {
173             norm.sample(&mut rng);
174             norm.ind_sample(&mut rng);
175         }
176     }
177     #[test]
178     #[should_fail]
179     fn test_normal_invalid_sd() {
180         Normal::new(10.0, -1.0);
181     }
182
183
184     #[test]
185     fn test_log_normal() {
186         let mut lnorm = LogNormal::new(10.0, 10.0);
187         let mut rng = ::test::rng();
188         for _ in range(0u, 1000) {
189             lnorm.sample(&mut rng);
190             lnorm.ind_sample(&mut rng);
191         }
192     }
193     #[test]
194     #[should_fail]
195     fn test_log_normal_invalid_sd() {
196         LogNormal::new(10.0, -1.0);
197     }
198 }
199
200 #[cfg(test)]
201 mod bench {
202     extern crate test;
203     use std::prelude::v1::*;
204     use self::test::Bencher;
205     use std::mem::size_of;
206     use distributions::{Sample};
207     use super::Normal;
208
209     #[bench]
210     fn rand_normal(b: &mut Bencher) {
211         let mut rng = ::test::weak_rng();
212         let mut normal = Normal::new(-2.71828, 3.14159);
213
214         b.iter(|| {
215             for _ in range(0, ::RAND_BENCH_N) {
216                 normal.sample(&mut rng);
217             }
218         });
219         b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
220     }
221 }