Skip to main content

rv/dist/
delta.rs

1use crate::{
2    impl_scalable, impl_shiftable,
3    traits::{
4        Cdf, ContinuousDistr, HasDensity, Mean, Median, Mode, Sampleable,
5        Scalable, Shiftable, Support,
6    },
7};
8
9/// A Dirac delta distribution
10///
11/// This is not a traditional distribution but rather a helpful device, as a dirac delta will
12/// always draw a value of 0 and has a cdf characterised by the Heaviside function centered at zero.
13///
14/// # Example
15/// ```rust
16/// use rv::prelude::*;
17/// use rv::dist::Delta;
18/// use rand;
19///
20/// let mut rng = rand::rng();
21/// let x: f64 = Delta.draw(&mut rng);
22///
23/// assert_eq!(x, 0.0);
24/// assert_eq!(Delta.cdf(&-1.0), 0.0);
25/// assert_eq!(Delta.cdf(&1.0), 1.0);
26/// ```
27pub struct Delta;
28
29macro_rules! trait_impls {
30    ($t: ty) => {
31        impl Sampleable<$t> for Delta {
32            fn draw<R: rand::Rng>(&self, _rng: &mut R) -> $t {
33                0.0
34            }
35        }
36
37        impl Cdf<$t> for Delta {
38            fn cdf(&self, x: &$t) -> f64 {
39                if x < &0.0 { 0.0 } else { 1.0 }
40            }
41        }
42
43        impl HasDensity<$t> for Delta {
44            fn ln_f(&self, x: &$t) -> f64 {
45                if x == &0.0 { f64::INFINITY } else { 0.0 }
46            }
47        }
48
49        impl Support<$t> for Delta {
50            fn supports(&self, _x: &$t) -> bool {
51                true
52            }
53        }
54
55        impl ContinuousDistr<$t> for Delta {}
56
57        impl Mean<$t> for Delta {
58            fn mean(&self) -> Option<$t> {
59                Some(0.0)
60            }
61        }
62
63        impl Mode<$t> for Delta {
64            fn mode(&self) -> Option<$t> {
65                Some(0.0)
66            }
67        }
68
69        impl Median<$t> for Delta {
70            fn median(&self) -> Option<$t> {
71                Some(0.0)
72            }
73        }
74    };
75}
76
77trait_impls!(f64);
78trait_impls!(f32);
79
80impl_shiftable!(Delta);
81impl_scalable!(Delta);