Skip to content

Commit aec5ba5

Browse files
committed
---
yaml --- r: 145830 b: refs/heads/try2 c: 38732c4 h: refs/heads/master v: v3
1 parent 5df7498 commit aec5ba5

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ refs/heads/snap-stage3: 78a7676898d9f80ab540c6df5d4c9ce35bb50463
55
refs/heads/try: 519addf6277dbafccbb4159db4b710c37eaa2ec5
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
8-
refs/heads/try2: a836f13dc0c2c636fd00b77d05f50a00cc3a7c55
8+
refs/heads/try2: 38732c4b5cf778cb1b441bfc4290b3e3524b80c2
99
refs/heads/dist-snap: ba4081a5a8573875fed17545846f6f6902c8ba8d
1010
refs/tags/release-0.2: c870d2dffb391e14efb05aa27898f1f6333a9596
1111
refs/tags/release-0.3: b5f0d0f648d9a6153664837026ba1be43d3e2503

branches/try2/src/libstd/rand/rand_impls.rs

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,23 +95,28 @@ impl Rand for u64 {
9595
}
9696

9797
impl Rand for f32 {
98-
/// A random `f32` in the range `[0, 1)`.
98+
/// A random `f32` in the range `[0, 1)`, using 24 bits of
99+
/// precision.
99100
#[inline]
100101
fn rand<R: Rng>(rng: &mut R) -> f32 {
101-
// weird, but this is the easiest way to get 2**32
102-
static SCALE: f32 = 2.0 * (1u32 << 31) as f32;
103-
rng.next_u32() as f32 / SCALE
102+
// using any more than 24 bits will cause (e.g.) 0xffff_ffff
103+
// to correspond to 1 exactly, so we need to drop 8 to
104+
// guarantee the open end.
105+
106+
static SCALE: f32 = (1u32 << 24) as f32;
107+
(rng.next_u32() >> 8) as f32 / SCALE
104108
}
105109
}
106110

107111
impl Rand for f64 {
108-
/// A random `f64` in the range `[0, 1)`.
112+
/// A random `f64` in the range `[0, 1)`, using 53 bits of
113+
/// precision.
109114
#[inline]
110115
fn rand<R: Rng>(rng: &mut R) -> f64 {
111-
// weird, but this is the easiest way to get 2**64
112-
static SCALE: f64 = 2.0 * (1u64 << 63) as f64;
116+
// as for f32, but using more bits.
113117

114-
rng.next_u64() as f64 / SCALE
118+
static SCALE: f64 = (1u64 << 53) as f64;
119+
(rng.next_u64() >> 11) as f64 / SCALE
115120
}
116121
}
117122

@@ -198,3 +203,19 @@ impl<T: Rand + 'static> Rand for @T {
198203
#[inline]
199204
fn rand<R: Rng>(rng: &mut R) -> @T { @rng.gen() }
200205
}
206+
207+
#[cfg(test)]
208+
mod tests {
209+
use rand::Rng;
210+
struct ConstantRng(u64);
211+
impl Rng for ConstantRng {
212+
fn next_u64(&mut self) -> u64 {
213+
**self
214+
}
215+
}
216+
fn floating_point_edge_cases() {
217+
// the test for exact equality is correct here.
218+
assert!(ConstantRng(0xffff_ffff).gen::<f32>() != 1.0)
219+
assert!(ConstantRng(0xffff_ffff_ffff_ffff).gen::<f64>() != 1.0)
220+
}
221+
}

0 commit comments

Comments
 (0)