Skip to content

Commit 3206b55

Browse files
committed
---
yaml --- r: 83804 b: refs/heads/try c: 38732c4 h: refs/heads/master v: v3
1 parent 8dde94c commit 3206b55

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
@@ -2,7 +2,7 @@
22
refs/heads/master: 0e4d1fc8cae42e15e00f71d9f439b01bb25a86ae
33
refs/heads/snap-stage1: e33de59e47c5076a89eadeb38f4934f58a3618a6
44
refs/heads/snap-stage3: 6c08cc2db4f98e9f07ae7d50338396c4123c2f0a
5-
refs/heads/try: a836f13dc0c2c636fd00b77d05f50a00cc3a7c55
5+
refs/heads/try: 38732c4b5cf778cb1b441bfc4290b3e3524b80c2
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
88
refs/heads/try2: 147ecfdd8221e4a4d4e090486829a06da1e0ca3c

branches/try/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)