]> git.lizzy.rs Git - rust.git/blob - src/librand/distributions/exponential.rs
rollup merge of #19577: aidancully/master
[rust.git] / src / librand / distributions / exponential.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 exponential distribution.
12
13 use core::kinds::Copy;
14 use core::num::Float;
15
16 use {Rng, Rand};
17 use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample};
18
19 /// A wrapper around an `f64` to generate Exp(1) random numbers.
20 ///
21 /// See `Exp` for the general exponential distribution.Note that this
22  // has to be unwrapped before use as an `f64` (using either
23 /// `*` or `mem::transmute` is safe).
24 ///
25 /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. The
26 /// exact description in the paper was adjusted to use tables for the
27 /// exponential distribution rather than normal.
28 ///
29 /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
30 /// Generate Normal Random
31 /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
32 /// College, Oxford
33 pub struct Exp1(pub f64);
34
35 impl Copy for Exp1 {}
36
37 // This could be done via `-rng.gen::<f64>().ln()` but that is slower.
38 impl Rand for Exp1 {
39     #[inline]
40     fn rand<R:Rng>(rng: &mut R) -> Exp1 {
41         #[inline]
42         fn pdf(x: f64) -> f64 {
43             (-x).exp()
44         }
45         #[inline]
46         fn zero_case<R:Rng>(rng: &mut R, _u: f64) -> f64 {
47             ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln()
48         }
49
50         Exp1(ziggurat(rng, false,
51                       &ziggurat_tables::ZIG_EXP_X,
52                       &ziggurat_tables::ZIG_EXP_F,
53                       pdf, zero_case))
54     }
55 }
56
57 /// The exponential distribution `Exp(lambda)`.
58 ///
59 /// This distribution has density function: `f(x) = lambda *
60 /// exp(-lambda * x)` for `x > 0`.
61 ///
62 /// # Example
63 ///
64 /// ```rust
65 /// use std::rand;
66 /// use std::rand::distributions::{Exp, IndependentSample};
67 ///
68 /// let exp = Exp::new(2.0);
69 /// let v = exp.ind_sample(&mut rand::task_rng());
70 /// println!("{} is from a Exp(2) distribution", v);
71 /// ```
72 pub struct Exp {
73     /// `lambda` stored as `1/lambda`, since this is what we scale by.
74     lambda_inverse: f64
75 }
76
77 impl Copy for Exp {}
78
79 impl Exp {
80     /// Construct a new `Exp` with the given shape parameter
81     /// `lambda`. Panics if `lambda <= 0`.
82     pub fn new(lambda: f64) -> Exp {
83         assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0");
84         Exp { lambda_inverse: 1.0 / lambda }
85     }
86 }
87
88 impl Sample<f64> for Exp {
89     fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
90 }
91 impl IndependentSample<f64> for Exp {
92     fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
93         let Exp1(n) = rng.gen::<Exp1>();
94         n * self.lambda_inverse
95     }
96 }
97
98 #[cfg(test)]
99 mod test {
100     use std::prelude::*;
101
102     use distributions::{Sample, IndependentSample};
103     use super::Exp;
104
105     #[test]
106     fn test_exp() {
107         let mut exp = Exp::new(10.0);
108         let mut rng = ::test::rng();
109         for _ in range(0u, 1000) {
110             assert!(exp.sample(&mut rng) >= 0.0);
111             assert!(exp.ind_sample(&mut rng) >= 0.0);
112         }
113     }
114     #[test]
115     #[should_fail]
116     fn test_exp_invalid_lambda_zero() {
117         Exp::new(0.0);
118     }
119     #[test]
120     #[should_fail]
121     fn test_exp_invalid_lambda_neg() {
122         Exp::new(-10.0);
123     }
124 }
125
126 #[cfg(test)]
127 mod bench {
128     extern crate test;
129
130     use std::prelude::*;
131
132     use self::test::Bencher;
133     use std::mem::size_of;
134     use super::Exp;
135     use distributions::Sample;
136
137     #[bench]
138     fn rand_exp(b: &mut Bencher) {
139         let mut rng = ::test::weak_rng();
140         let mut exp = Exp::new(2.71828 * 3.14159);
141
142         b.iter(|| {
143             for _ in range(0, ::RAND_BENCH_N) {
144                 exp.sample(&mut rng);
145             }
146         });
147         b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N;
148     }
149 }