]> git.proxmox.com Git - cargo.git/blob - vendor/rand-0.5.6/src/distributions/float.rs
New upstream version 0.33.0
[cargo.git] / vendor / rand-0.5.6 / src / distributions / float.rs
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.
4 //
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.
10
11 //! Basic floating-point number distributions
12
13 use core::mem;
14 use Rng;
15 use distributions::{Distribution, Standard};
16
17 /// A distribution to sample floating point numbers uniformly in the half-open
18 /// interval `(0, 1]`, i.e. including 1 but not 0.
19 ///
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.
24 ///
25 /// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`]
26 /// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary
27 /// ranges.
28 ///
29 /// # Example
30 /// ```
31 /// use rand::{thread_rng, Rng};
32 /// use rand::distributions::OpenClosed01;
33 ///
34 /// let val: f32 = thread_rng().sample(OpenClosed01);
35 /// println!("f32 from (0, 1): {}", val);
36 /// ```
37 ///
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;
43
44 /// A distribution to sample floating point numbers uniformly in the open
45 /// interval `(0, 1)`, i.e. not including either endpoint.
46 ///
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.
50 ///
51 /// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`]
52 /// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary
53 /// ranges.
54 ///
55 /// # Example
56 /// ```
57 /// use rand::{thread_rng, Rng};
58 /// use rand::distributions::Open01;
59 ///
60 /// let val: f32 = thread_rng().sample(Open01);
61 /// println!("f32 from (0, 1): {}", val);
62 /// ```
63 ///
64 /// [`Standard`]: struct.Standard.html
65 /// [`OpenClosed01`]: struct.OpenClosed01.html
66 /// [`Uniform`]: uniform/struct.Uniform.html
67 #[derive(Clone, Copy, Debug)]
68 pub struct Open01;
69
70
71 pub(crate) trait IntoFloat {
72 type F;
73
74 /// Helper method to combine the fraction and a contant exponent into a
75 /// float.
76 ///
77 /// Only the least significant bits of `self` may be set, 23 for `f32` and
78 /// 52 for `f64`.
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;
83 }
84
85 macro_rules! float_impls {
86 ($ty:ty, $uty:ty, $fraction_bits:expr, $exponent_bias:expr) => {
87 impl IntoFloat for $uty {
88 type F = $ty;
89 #[inline(always)]
90 fn into_float_with_exponent(self, exponent: i32) -> $ty {
91 // The exponent is encoded using an offset-binary representation
92 let exponent_bits =
93 (($exponent_bias + exponent) as $uty) << $fraction_bits;
94 unsafe { mem::transmute(self | exponent_bits) }
95 }
96 }
97
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);
106
107 let value: $uty = rng.gen();
108 scale * (value >> (float_size - precision)) as $ty
109 }
110 }
111
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);
120
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
125 }
126 }
127
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;
135
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)
139 }
140 }
141 }
142 }
143 float_impls! { f32, u32, 23, 127 }
144 float_impls! { f64, u64, 52, 1023 }
145
146
147 #[cfg(test)]
148 mod tests {
149 use Rng;
150 use distributions::{Open01, OpenClosed01};
151 use rngs::mock::StepRng;
152
153 const EPSILON32: f32 = ::core::f32::EPSILON;
154 const EPSILON64: f64 = ::core::f64::EPSILON;
155
156 #[test]
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);
161
162 let mut one32 = StepRng::new(1 << 8, 0);
163 assert_eq!(one32.gen::<f32>(), EPSILON32 / 2.0);
164
165 let mut one64 = StepRng::new(1 << 11, 0);
166 assert_eq!(one64.gen::<f64>(), EPSILON64 / 2.0);
167
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);
171 }
172
173 #[test]
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);
178
179 let mut one32 = StepRng::new(1 << 8, 0);
180 assert_eq!(one32.sample::<f32, _>(OpenClosed01), EPSILON32);
181
182 let mut one64 = StepRng::new(1 << 11, 0);
183 assert_eq!(one64.sample::<f64, _>(OpenClosed01), EPSILON64);
184
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);
188 }
189
190 #[test]
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);
195
196 let mut one32 = StepRng::new(1 << 9, 0);
197 assert_eq!(one32.sample::<f32, _>(Open01), EPSILON32 / 2.0 * 3.0);
198
199 let mut one64 = StepRng::new(1 << 12, 0);
200 assert_eq!(one64.sample::<f64, _>(Open01), EPSILON64 / 2.0 * 3.0);
201
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);
205 }
206 }