1use crate::distr::utils::{FloatAsSIMD, FloatSIMDUtils, IntAsSIMD};
12use crate::distr::{Distribution, StandardUniform};
13use crate::Rng;
14use core::mem;
15#[cfg(feature = "simd_support")]
16use core::simd::prelude::*;
17
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize};
20
21#[derive(Clone, Copy, Debug, Default)]
46#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
47pub struct OpenClosed01;
48
49#[derive(Clone, Copy, Debug, Default)]
73#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
74pub struct Open01;
75
76#[doc(hidden)]
78pub trait IntoFloat {
79    type F;
80
81    fn into_float_with_exponent(self, exponent: i32) -> Self::F;
90}
91
92macro_rules! float_impls {
93    ($($meta:meta)?, $ty:ident, $uty:ident, $f_scalar:ident, $u_scalar:ty,
94     $fraction_bits:expr, $exponent_bias:expr) => {
95        $(#[cfg($meta)])?
96        impl IntoFloat for $uty {
97            type F = $ty;
98            #[inline(always)]
99            fn into_float_with_exponent(self, exponent: i32) -> $ty {
100                let exponent_bits: $u_scalar =
102                    (($exponent_bias + exponent) as $u_scalar) << $fraction_bits;
103                $ty::from_bits(self | $uty::splat(exponent_bits))
104            }
105        }
106
107        $(#[cfg($meta)])?
108        impl Distribution<$ty> for StandardUniform {
109            fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
110                let float_size = mem::size_of::<$f_scalar>() as $u_scalar * 8;
114                let precision = $fraction_bits + 1;
115                let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar);
116
117                let value: $uty = rng.random();
118                let value = value >> $uty::splat(float_size - precision);
119                $ty::splat(scale) * $ty::cast_from_int(value)
120            }
121        }
122
123        $(#[cfg($meta)])?
124        impl Distribution<$ty> for OpenClosed01 {
125            fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
126                let float_size = mem::size_of::<$f_scalar>() as $u_scalar * 8;
130                let precision = $fraction_bits + 1;
131                let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar);
132
133                let value: $uty = rng.random();
134                let value = value >> $uty::splat(float_size - precision);
135                $ty::splat(scale) * $ty::cast_from_int(value + $uty::splat(1))
137            }
138        }
139
140        $(#[cfg($meta)])?
141        impl Distribution<$ty> for Open01 {
142            fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
143                let float_size = mem::size_of::<$f_scalar>() as $u_scalar * 8;
147
148                let value: $uty = rng.random();
149                let fraction = value >> $uty::splat(float_size - $fraction_bits);
150                fraction.into_float_with_exponent(0) - $ty::splat(1.0 - $f_scalar::EPSILON / 2.0)
151            }
152        }
153    }
154}
155
156float_impls! { , f32, u32, f32, u32, 23, 127 }
157float_impls! { , f64, u64, f64, u64, 52, 1023 }
158
159#[cfg(feature = "simd_support")]
160float_impls! { feature = "simd_support", f32x2, u32x2, f32, u32, 23, 127 }
161#[cfg(feature = "simd_support")]
162float_impls! { feature = "simd_support", f32x4, u32x4, f32, u32, 23, 127 }
163#[cfg(feature = "simd_support")]
164float_impls! { feature = "simd_support", f32x8, u32x8, f32, u32, 23, 127 }
165#[cfg(feature = "simd_support")]
166float_impls! { feature = "simd_support", f32x16, u32x16, f32, u32, 23, 127 }
167
168#[cfg(feature = "simd_support")]
169float_impls! { feature = "simd_support", f64x2, u64x2, f64, u64, 52, 1023 }
170#[cfg(feature = "simd_support")]
171float_impls! { feature = "simd_support", f64x4, u64x4, f64, u64, 52, 1023 }
172#[cfg(feature = "simd_support")]
173float_impls! { feature = "simd_support", f64x8, u64x8, f64, u64, 52, 1023 }
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::test::const_rng;
179
180    const EPSILON32: f32 = f32::EPSILON;
181    const EPSILON64: f64 = f64::EPSILON;
182
183    macro_rules! test_f32 {
184        ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => {
185            #[test]
186            fn $fnn() {
187                let two = $ty::splat(2.0);
188
189                let mut zeros = const_rng(0);
191                assert_eq!(zeros.random::<$ty>(), $ZERO);
192                let mut one = const_rng(1 << 8 | 1 << (8 + 32));
193                assert_eq!(one.random::<$ty>(), $EPSILON / two);
194                let mut max = const_rng(!0);
195                assert_eq!(max.random::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
196
197                let mut zeros = const_rng(0);
199                assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), $ZERO + $EPSILON / two);
200                let mut one = const_rng(1 << 8 | 1 << (8 + 32));
201                assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON);
202                let mut max = const_rng(!0);
203                assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + $ty::splat(1.0));
204
205                let mut zeros = const_rng(0);
207                assert_eq!(zeros.sample::<$ty, _>(Open01), $ZERO + $EPSILON / two);
208                let mut one = const_rng(1 << 9 | 1 << (9 + 32));
209                assert_eq!(
210                    one.sample::<$ty, _>(Open01),
211                    $EPSILON / two * $ty::splat(3.0)
212                );
213                let mut max = const_rng(!0);
214                assert_eq!(
215                    max.sample::<$ty, _>(Open01),
216                    $ty::splat(1.0) - $EPSILON / two
217                );
218            }
219        };
220    }
221    test_f32! { f32_edge_cases, f32, 0.0, EPSILON32 }
222    #[cfg(feature = "simd_support")]
223    test_f32! { f32x2_edge_cases, f32x2, f32x2::splat(0.0), f32x2::splat(EPSILON32) }
224    #[cfg(feature = "simd_support")]
225    test_f32! { f32x4_edge_cases, f32x4, f32x4::splat(0.0), f32x4::splat(EPSILON32) }
226    #[cfg(feature = "simd_support")]
227    test_f32! { f32x8_edge_cases, f32x8, f32x8::splat(0.0), f32x8::splat(EPSILON32) }
228    #[cfg(feature = "simd_support")]
229    test_f32! { f32x16_edge_cases, f32x16, f32x16::splat(0.0), f32x16::splat(EPSILON32) }
230
231    macro_rules! test_f64 {
232        ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => {
233            #[test]
234            fn $fnn() {
235                let two = $ty::splat(2.0);
236
237                let mut zeros = const_rng(0);
239                assert_eq!(zeros.random::<$ty>(), $ZERO);
240                let mut one = const_rng(1 << 11);
241                assert_eq!(one.random::<$ty>(), $EPSILON / two);
242                let mut max = const_rng(!0);
243                assert_eq!(max.random::<$ty>(), $ty::splat(1.0) - $EPSILON / two);
244
245                let mut zeros = const_rng(0);
247                assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), $ZERO + $EPSILON / two);
248                let mut one = const_rng(1 << 11);
249                assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON);
250                let mut max = const_rng(!0);
251                assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + $ty::splat(1.0));
252
253                let mut zeros = const_rng(0);
255                assert_eq!(zeros.sample::<$ty, _>(Open01), $ZERO + $EPSILON / two);
256                let mut one = const_rng(1 << 12);
257                assert_eq!(
258                    one.sample::<$ty, _>(Open01),
259                    $EPSILON / two * $ty::splat(3.0)
260                );
261                let mut max = const_rng(!0);
262                assert_eq!(
263                    max.sample::<$ty, _>(Open01),
264                    $ty::splat(1.0) - $EPSILON / two
265                );
266            }
267        };
268    }
269    test_f64! { f64_edge_cases, f64, 0.0, EPSILON64 }
270    #[cfg(feature = "simd_support")]
271    test_f64! { f64x2_edge_cases, f64x2, f64x2::splat(0.0), f64x2::splat(EPSILON64) }
272    #[cfg(feature = "simd_support")]
273    test_f64! { f64x4_edge_cases, f64x4, f64x4::splat(0.0), f64x4::splat(EPSILON64) }
274    #[cfg(feature = "simd_support")]
275    test_f64! { f64x8_edge_cases, f64x8, f64x8::splat(0.0), f64x8::splat(EPSILON64) }
276
277    #[test]
278    fn value_stability() {
279        fn test_samples<T: Copy + core::fmt::Debug + PartialEq, D: Distribution<T>>(
280            distr: &D,
281            zero: T,
282            expected: &[T],
283        ) {
284            let mut rng = crate::test::rng(0x6f44f5646c2a7334);
285            let mut buf = [zero; 3];
286            for x in &mut buf {
287                *x = rng.sample(distr);
288            }
289            assert_eq!(&buf, expected);
290        }
291
292        test_samples(
293            &StandardUniform,
294            0f32,
295            &[0.0035963655, 0.7346052, 0.09778172],
296        );
297        test_samples(
298            &StandardUniform,
299            0f64,
300            &[0.7346051961657583, 0.20298547462974248, 0.8166436635290655],
301        );
302
303        test_samples(&OpenClosed01, 0f32, &[0.003596425, 0.73460525, 0.09778178]);
304        test_samples(
305            &OpenClosed01,
306            0f64,
307            &[0.7346051961657584, 0.2029854746297426, 0.8166436635290656],
308        );
309
310        test_samples(&Open01, 0f32, &[0.0035963655, 0.73460525, 0.09778172]);
311        test_samples(
312            &Open01,
313            0f64,
314            &[0.7346051961657584, 0.20298547462974248, 0.8166436635290656],
315        );
316
317        #[cfg(feature = "simd_support")]
318        {
319            test_samples(
324                &StandardUniform,
325                f32x2::from([0.0, 0.0]),
326                &[
327                    f32x2::from([0.0035963655, 0.7346052]),
328                    f32x2::from([0.09778172, 0.20298547]),
329                    f32x2::from([0.34296435, 0.81664366]),
330                ],
331            );
332
333            test_samples(
334                &StandardUniform,
335                f64x2::from([0.0, 0.0]),
336                &[
337                    f64x2::from([0.7346051961657583, 0.20298547462974248]),
338                    f64x2::from([0.8166436635290655, 0.7423708925400552]),
339                    f64x2::from([0.16387782224016323, 0.9087068770169618]),
340                ],
341            );
342        }
343    }
344}