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