1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // https://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Basic floating-point number distributions
15 use distributions
::{Distribution, Standard}
;
17 /// A distribution to sample floating point numbers uniformly in the half-open
18 /// interval `(0, 1]`, i.e. including 1 but not 0.
20 /// All values that can be generated are of the form `n * ε/2`. For `f32`
21 /// the 23 most significant random bits of a `u32` are used and for `f64` the
22 /// 53 most significant bits of a `u64` are used. The conversion uses the
23 /// multiplicative method.
25 /// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`]
26 /// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary
31 /// use rand::{thread_rng, Rng};
32 /// use rand::distributions::OpenClosed01;
34 /// let val: f32 = thread_rng().sample(OpenClosed01);
35 /// println!("f32 from (0, 1): {}", val);
38 /// [`Standard`]: struct.Standard.html
39 /// [`Open01`]: struct.Open01.html
40 /// [`Uniform`]: uniform/struct.Uniform.html
41 #[derive(Clone, Copy, Debug)]
42 pub struct OpenClosed01
;
44 /// A distribution to sample floating point numbers uniformly in the open
45 /// interval `(0, 1)`, i.e. not including either endpoint.
47 /// All values that can be generated are of the form `n * ε + ε/2`. For `f32`
48 /// the 22 most significant random bits of an `u32` are used, for `f64` 52 from
49 /// an `u64`. The conversion uses a transmute-based method.
51 /// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`]
52 /// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary
57 /// use rand::{thread_rng, Rng};
58 /// use rand::distributions::Open01;
60 /// let val: f32 = thread_rng().sample(Open01);
61 /// println!("f32 from (0, 1): {}", val);
64 /// [`Standard`]: struct.Standard.html
65 /// [`OpenClosed01`]: struct.OpenClosed01.html
66 /// [`Uniform`]: uniform/struct.Uniform.html
67 #[derive(Clone, Copy, Debug)]
71 pub(crate) trait IntoFloat
{
74 /// Helper method to combine the fraction and a contant exponent into a
77 /// Only the least significant bits of `self` may be set, 23 for `f32` and
79 /// The resulting value will fall in a range that depends on the exponent.
80 /// As an example the range with exponent 0 will be
81 /// [2<sup>0</sup>..2<sup>1</sup>), which is [1..2).
82 fn into_float_with_exponent(self, exponent
: i32) -> Self::F
;
85 macro_rules
! float_impls
{
86 ($ty
:ty
, $uty
:ty
, $fraction_bits
:expr
, $exponent_bias
:expr
) => {
87 impl IntoFloat
for $uty
{
90 fn into_float_with_exponent(self, exponent
: i32) -> $ty
{
91 // The exponent is encoded using an offset-binary representation
93 (($exponent_bias
+ exponent
) as $uty
) << $fraction_bits
;
94 unsafe { mem::transmute(self | exponent_bits) }
98 impl Distribution
<$ty
> for Standard
{
99 fn sample
<R
: Rng
+ ?Sized
>(&self, rng
: &mut R
) -> $ty
{
100 // Multiply-based method; 24/53 random bits; [0, 1) interval.
101 // We use the most significant bits because for simple RNGs
102 // those are usually more random.
103 let float_size
= mem
::size_of
::<$ty
>() * 8;
104 let precision
= $fraction_bits
+ 1;
105 let scale
= 1.0 / ((1 as $uty
<< precision
) as $ty
);
107 let value
: $uty
= rng
.gen();
108 scale
* (value
>> (float_size
- precision
)) as $ty
112 impl Distribution
<$ty
> for OpenClosed01
{
113 fn sample
<R
: Rng
+ ?Sized
>(&self, rng
: &mut R
) -> $ty
{
114 // Multiply-based method; 24/53 random bits; (0, 1] interval.
115 // We use the most significant bits because for simple RNGs
116 // those are usually more random.
117 let float_size
= mem
::size_of
::<$ty
>() * 8;
118 let precision
= $fraction_bits
+ 1;
119 let scale
= 1.0 / ((1 as $uty
<< precision
) as $ty
);
121 let value
: $uty
= rng
.gen();
122 let value
= value
>> (float_size
- precision
);
123 // Add 1 to shift up; will not overflow because of right-shift:
124 scale
* (value
+ 1) as $ty
128 impl Distribution
<$ty
> for Open01
{
129 fn sample
<R
: Rng
+ ?Sized
>(&self, rng
: &mut R
) -> $ty
{
130 // Transmute-based method; 23/52 random bits; (0, 1) interval.
131 // We use the most significant bits because for simple RNGs
132 // those are usually more random.
133 const EPSILON
: $ty
= 1.0 / (1u64 << $fraction_bits
) as $ty
;
134 let float_size
= mem
::size_of
::<$ty
>() * 8;
136 let value
: $uty
= rng
.gen();
137 let fraction
= value
>> (float_size
- $fraction_bits
);
138 fraction
.into_float_with_exponent(0) - (1.0 - EPSILON
/ 2.0)
143 float_impls
! { f32, u32, 23, 127 }
144 float_impls
! { f64, u64, 52, 1023 }
150 use distributions
::{Open01, OpenClosed01}
;
151 use rngs
::mock
::StepRng
;
153 const EPSILON32
: f32 = ::core
::f32::EPSILON
;
154 const EPSILON64
: f64 = ::core
::f64::EPSILON
;
157 fn standard_fp_edge_cases() {
158 let mut zeros
= StepRng
::new(0, 0);
159 assert_eq
!(zeros
.gen
::<f32>(), 0.0);
160 assert_eq
!(zeros
.gen
::<f64>(), 0.0);
162 let mut one32
= StepRng
::new(1 << 8, 0);
163 assert_eq
!(one32
.gen
::<f32>(), EPSILON32
/ 2.0);
165 let mut one64
= StepRng
::new(1 << 11, 0);
166 assert_eq
!(one64
.gen
::<f64>(), EPSILON64
/ 2.0);
168 let mut max
= StepRng
::new(!0, 0);
169 assert_eq
!(max
.gen
::<f32>(), 1.0 - EPSILON32
/ 2.0);
170 assert_eq
!(max
.gen
::<f64>(), 1.0 - EPSILON64
/ 2.0);
174 fn openclosed01_edge_cases() {
175 let mut zeros
= StepRng
::new(0, 0);
176 assert_eq
!(zeros
.sample
::<f32, _
>(OpenClosed01
), 0.0 + EPSILON32
/ 2.0);
177 assert_eq
!(zeros
.sample
::<f64, _
>(OpenClosed01
), 0.0 + EPSILON64
/ 2.0);
179 let mut one32
= StepRng
::new(1 << 8, 0);
180 assert_eq
!(one32
.sample
::<f32, _
>(OpenClosed01
), EPSILON32
);
182 let mut one64
= StepRng
::new(1 << 11, 0);
183 assert_eq
!(one64
.sample
::<f64, _
>(OpenClosed01
), EPSILON64
);
185 let mut max
= StepRng
::new(!0, 0);
186 assert_eq
!(max
.sample
::<f32, _
>(OpenClosed01
), 1.0);
187 assert_eq
!(max
.sample
::<f64, _
>(OpenClosed01
), 1.0);
191 fn open01_edge_cases() {
192 let mut zeros
= StepRng
::new(0, 0);
193 assert_eq
!(zeros
.sample
::<f32, _
>(Open01
), 0.0 + EPSILON32
/ 2.0);
194 assert_eq
!(zeros
.sample
::<f64, _
>(Open01
), 0.0 + EPSILON64
/ 2.0);
196 let mut one32
= StepRng
::new(1 << 9, 0);
197 assert_eq
!(one32
.sample
::<f32, _
>(Open01
), EPSILON32
/ 2.0 * 3.0);
199 let mut one64
= StepRng
::new(1 << 12, 0);
200 assert_eq
!(one64
.sample
::<f64, _
>(Open01
), EPSILON64
/ 2.0 * 3.0);
202 let mut max
= StepRng
::new(!0, 0);
203 assert_eq
!(max
.sample
::<f32, _
>(Open01
), 1.0 - EPSILON32
/ 2.0);
204 assert_eq
!(max
.sample
::<f64, _
>(Open01
), 1.0 - EPSILON64
/ 2.0);