1use crate::{Distribution, OpenClosed01};
12use core::fmt;
13use num_traits::Float;
14use rand::Rng;
15
16#[derive(Clone, Copy, Debug, PartialEq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct Pareto<F>
41where
42 F: Float,
43 OpenClosed01: Distribution<F>,
44{
45 scale: F,
46 inv_neg_shape: F,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum Error {
52 ScaleTooSmall,
54 ShapeTooSmall,
56}
57
58impl fmt::Display for Error {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 f.write_str(match self {
61 Error::ScaleTooSmall => "scale is not positive in Pareto distribution",
62 Error::ShapeTooSmall => "shape is not positive in Pareto distribution",
63 })
64 }
65}
66
67#[cfg(feature = "std")]
68impl std::error::Error for Error {}
69
70impl<F> Pareto<F>
71where
72 F: Float,
73 OpenClosed01: Distribution<F>,
74{
75 pub fn new(scale: F, shape: F) -> Result<Pareto<F>, Error> {
80 let zero = F::zero();
81
82 if !(scale > zero) {
83 return Err(Error::ScaleTooSmall);
84 }
85 if !(shape > zero) {
86 return Err(Error::ShapeTooSmall);
87 }
88 Ok(Pareto {
89 scale,
90 inv_neg_shape: F::from(-1.0).unwrap() / shape,
91 })
92 }
93}
94
95impl<F> Distribution<F> for Pareto<F>
96where
97 F: Float,
98 OpenClosed01: Distribution<F>,
99{
100 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
101 let u: F = OpenClosed01.sample(rng);
102 self.scale * u.powf(self.inv_neg_shape)
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109 use core::fmt::{Debug, Display, LowerExp};
110
111 #[test]
112 #[should_panic]
113 fn invalid() {
114 Pareto::new(0., 0.).unwrap();
115 }
116
117 #[test]
118 fn sample() {
119 let scale = 1.0;
120 let shape = 2.0;
121 let d = Pareto::new(scale, shape).unwrap();
122 let mut rng = crate::test::rng(1);
123 for _ in 0..1000 {
124 let r = d.sample(&mut rng);
125 assert!(r >= scale);
126 }
127 }
128
129 #[test]
130 fn value_stability() {
131 fn test_samples<F: Float + Debug + Display + LowerExp, D: Distribution<F>>(
132 distr: D,
133 thresh: F,
134 expected: &[F],
135 ) {
136 let mut rng = crate::test::rng(213);
137 for v in expected {
138 let x = rng.sample(&distr);
139 assert_almost_eq!(x, *v, thresh);
140 }
141 }
142
143 test_samples(
144 Pareto::new(1f32, 1.0).unwrap(),
145 1e-6,
146 &[1.0423688, 2.1235929, 4.132709, 1.4679428],
147 );
148 test_samples(
149 Pareto::new(2.0, 0.5).unwrap(),
150 1e-14,
151 &[
152 9.019295276219136,
153 4.3097126018270595,
154 6.837815045397157,
155 105.8826669383772,
156 ],
157 );
158 }
159
160 #[test]
161 fn pareto_distributions_can_be_compared() {
162 assert_eq!(Pareto::new(1.0, 2.0), Pareto::new(1.0, 2.0));
163 }
164}