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 `Exp(λ)`.
11
12use crate::utils::ziggurat;
13use crate::{ziggurat_tables, Distribution};
14use core::fmt;
15use num_traits::Float;
16use rand::Rng;
17
18/// The standard exponential distribution `Exp(1)`.
19///
20/// This is equivalent to `Exp::new(1.0)` or sampling with
21/// `-rng.gen::<f64>().ln()`, but faster.
22///
23/// See [`Exp`](crate::Exp) for the general exponential distribution.
24///
25/// # Plot
26///
27/// The following plot illustrates the exponential distribution with `λ = 1`.
28///
29/// 
30///
31/// # Example
32///
33/// ```
34/// use rand::prelude::*;
35/// use rand_distr::Exp1;
36///
37/// let val: f64 = rand::rng().sample(Exp1);
38/// println!("{}", val);
39/// ```
40///
41/// # Notes
42///
43/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact
44/// description in the paper was adjusted to use tables for the exponential
45/// distribution rather than normal.
46///
47/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to
48/// Generate Normal Random Samples*](
49/// https://www.doornik.com/research/ziggurat.pdf).
50/// Nuffield College, Oxford
51#[derive(Clone, Copy, Debug)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub struct Exp1;
54
55impl Distribution<f32> for Exp1 {
56 #[inline]
57 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
58 // TODO: use optimal 32-bit implementation
59 let x: f64 = self.sample(rng);
60 x as f32
61 }
62}
63
64// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
65impl Distribution<f64> for Exp1 {
66 #[inline]
67 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
68 #[inline]
69 fn pdf(x: f64) -> f64 {
70 (-x).exp()
71 }
72 #[inline]
73 fn zero_case<R: Rng + ?Sized>(rng: &mut R, _u: f64) -> f64 {
74 ziggurat_tables::ZIG_EXP_R - rng.random::<f64>().ln()
75 }
76
77 ziggurat(
78 rng,
79 false,
80 &ziggurat_tables::ZIG_EXP_X,
81 &ziggurat_tables::ZIG_EXP_F,
82 pdf,
83 zero_case,
84 )
85 }
86}
87
88/// The [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution) `Exp(λ)`.
89///
90/// The exponential distribution is a continuous probability distribution
91/// with rate parameter `λ` (`lambda`). It describes the time between events
92/// in a [`Poisson`](crate::Poisson) process, i.e. a process in which
93/// events occur continuously and independently at a constant average rate.
94///
95/// See [`Exp1`](crate::Exp1) for an optimised implementation for `λ = 1`.
96///
97/// # Density function
98///
99/// `f(x) = λ * exp(-λ * x)` for `x > 0`, when `λ > 0`.
100///
101/// For `λ = 0`, all samples yield infinity (because a Poisson process
102/// with rate 0 has no events).
103///
104/// # Plot
105///
106/// The following plot illustrates the exponential distribution with
107/// various values of `λ`.
108/// The `λ` parameter controls the rate of decay as `x` approaches infinity,
109/// and the mean of the distribution is `1/λ`.
110///
111/// 
112///
113/// # Example
114///
115/// ```
116/// use rand_distr::{Exp, Distribution};
117///
118/// let exp = Exp::new(2.0).unwrap();
119/// let v = exp.sample(&mut rand::rng());
120/// println!("{} is from a Exp(2) distribution", v);
121/// ```
122#[derive(Clone, Copy, Debug, PartialEq)]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
124pub struct Exp<F>
125where
126 F: Float,
127 Exp1: Distribution<F>,
128{
129 /// `lambda` stored as `1/lambda`, since this is what we scale by.
130 lambda_inverse: F,
131}
132
133/// Error type returned from [`Exp::new`].
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub enum Error {
136 /// `lambda < 0` or `nan`.
137 LambdaTooSmall,
138}
139
140impl fmt::Display for Error {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.write_str(match self {
143 Error::LambdaTooSmall => "lambda is negative or NaN in exponential distribution",
144 })
145 }
146}
147
148#[cfg(feature = "std")]
149impl std::error::Error for Error {}
150
151impl<F: Float> Exp<F>
152where
153 F: Float,
154 Exp1: Distribution<F>,
155{
156 /// Construct a new `Exp` with the given shape parameter
157 /// `lambda`.
158 ///
159 /// # Remarks
160 ///
161 /// For custom types `N` implementing the [`Float`] trait,
162 /// the case `lambda = 0` is handled as follows: each sample corresponds
163 /// to a sample from an `Exp1` multiplied by `1 / 0`. Primitive types
164 /// yield infinity, since `1 / 0 = infinity`.
165 #[inline]
166 pub fn new(lambda: F) -> Result<Exp<F>, Error> {
167 if !(lambda >= F::zero()) {
168 return Err(Error::LambdaTooSmall);
169 }
170 Ok(Exp {
171 lambda_inverse: F::one() / lambda,
172 })
173 }
174}
175
176impl<F> Distribution<F> for Exp<F>
177where
178 F: Float,
179 Exp1: Distribution<F>,
180{
181 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
182 rng.sample(Exp1) * self.lambda_inverse
183 }
184}
185
186#[cfg(test)]
187mod test {
188 use super::*;
189
190 #[test]
191 fn test_exp() {
192 let exp = Exp::new(10.0).unwrap();
193 let mut rng = crate::test::rng(221);
194 for _ in 0..1000 {
195 assert!(exp.sample(&mut rng) >= 0.0);
196 }
197 }
198 #[test]
199 fn test_zero() {
200 let d = Exp::new(0.0).unwrap();
201 assert_eq!(d.sample(&mut crate::test::rng(21)), f64::infinity());
202 }
203 #[test]
204 #[should_panic]
205 fn test_exp_invalid_lambda_neg() {
206 Exp::new(-10.0).unwrap();
207 }
208
209 #[test]
210 #[should_panic]
211 fn test_exp_invalid_lambda_nan() {
212 Exp::new(f64::nan()).unwrap();
213 }
214
215 #[test]
216 fn exponential_distributions_can_be_compared() {
217 assert_eq!(Exp::new(1.0), Exp::new(1.0));
218 }
219}