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