rand_distr/exponential.rs
1// Copyright 2018 Developers of the Rand project.
2// Copyright 2013 The Rust Project Developers.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! The exponential distribution.
11
12use crate::utils::ziggurat;
13use num_traits::Float;
14use crate::{ziggurat_tables, Distribution};
15use rand::Rng;
16use core::fmt;
17
18/// Samples floating-point numbers according to the exponential distribution,
19/// with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or
20/// sampling with `-rng.gen::<f64>().ln()`, but faster.
21///
22/// See `Exp` for the general exponential distribution.
23///
24/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact
25/// description in the paper was adjusted to use tables for the exponential
26/// distribution rather than normal.
27///
28/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
29/// Generate Normal Random Samples*](
30/// https://www.doornik.com/research/ziggurat.pdf).
31/// Nuffield College, Oxford
32///
33/// # Example
34/// ```
35/// use rand::prelude::*;
36/// use rand_distr::Exp1;
37///
38/// let val: f64 = thread_rng().sample(Exp1);
39/// println!("{}", val);
40/// ```
41#[derive(Clone, Copy, Debug)]
42#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
43pub struct Exp1;
44
45impl Distribution<f32> for Exp1 {
46 #[inline]
47 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
48 // TODO: use optimal 32-bit implementation
49 let x: f64 = self.sample(rng);
50 x as f32
51 }
52}
53
54// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
55impl Distribution<f64> for Exp1 {
56 #[inline]
57 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
58 #[inline]
59 fn pdf(x: f64) -> f64 {
60 (-x).exp()
61 }
62 #[inline]
63 fn zero_case<R: Rng + ?Sized>(rng: &mut R, _u: f64) -> f64 {
64 ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln()
65 }
66
67 ziggurat(
68 rng,
69 false,
70 &ziggurat_tables::ZIG_EXP_X,
71 &ziggurat_tables::ZIG_EXP_F,
72 pdf,
73 zero_case,
74 )
75 }
76}
77
78/// The exponential distribution `Exp(lambda)`.
79///
80/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)`
81/// for `x > 0`, when `lambda > 0`. For `lambda = 0`, all samples yield infinity.
82///
83/// Note that [`Exp1`](crate::Exp1) is an optimised implementation for `lambda = 1`.
84///
85/// # Example
86///
87/// ```
88/// use rand_distr::{Exp, Distribution};
89///
90/// let exp = Exp::new(2.0).unwrap();
91/// let v = exp.sample(&mut rand::thread_rng());
92/// println!("{} is from a Exp(2) distribution", v);
93/// ```
94#[derive(Clone, Copy, Debug)]
95#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
96pub struct Exp<F>
97where F: Float, Exp1: Distribution<F>
98{
99 /// `lambda` stored as `1/lambda`, since this is what we scale by.
100 lambda_inverse: F,
101}
102
103/// Error type returned from `Exp::new`.
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub enum Error {
106 /// `lambda < 0` or `nan`.
107 LambdaTooSmall,
108}
109
110impl fmt::Display for Error {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.write_str(match self {
113 Error::LambdaTooSmall => "lambda is negative or NaN in exponential distribution",
114 })
115 }
116}
117
118#[cfg(feature = "std")]
119#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
120impl std::error::Error for Error {}
121
122impl<F: Float> Exp<F>
123where F: Float, Exp1: Distribution<F>
124{
125 /// Construct a new `Exp` with the given shape parameter
126 /// `lambda`.
127 ///
128 /// # Remarks
129 ///
130 /// For custom types `N` implementing the [`Float`] trait,
131 /// the case `lambda = 0` is handled as follows: each sample corresponds
132 /// to a sample from an `Exp1` multiplied by `1 / 0`. Primitive types
133 /// yield infinity, since `1 / 0 = infinity`.
134 #[inline]
135 pub fn new(lambda: F) -> Result<Exp<F>, Error> {
136 if !(lambda >= F::zero()) {
137 return Err(Error::LambdaTooSmall);
138 }
139 Ok(Exp {
140 lambda_inverse: F::one() / lambda,
141 })
142 }
143}
144
145impl<F> Distribution<F> for Exp<F>
146where F: Float, Exp1: Distribution<F>
147{
148 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
149 rng.sample(Exp1) * self.lambda_inverse
150 }
151}
152
153#[cfg(test)]
154mod test {
155 use super::*;
156
157 #[test]
158 fn test_exp() {
159 let exp = Exp::new(10.0).unwrap();
160 let mut rng = crate::test::rng(221);
161 for _ in 0..1000 {
162 assert!(exp.sample(&mut rng) >= 0.0);
163 }
164 }
165 #[test]
166 fn test_zero() {
167 let d = Exp::new(0.0).unwrap();
168 assert_eq!(d.sample(&mut crate::test::rng(21)), f64::infinity());
169 }
170 #[test]
171 #[should_panic]
172 fn test_exp_invalid_lambda_neg() {
173 Exp::new(-10.0).unwrap();
174 }
175
176 #[test]
177 #[should_panic]
178 fn test_exp_invalid_lambda_nan() {
179 Exp::new(f64::nan()).unwrap();
180 }
181}