diff options
| author | Jed Davis <jld@panix.com> | 2012-07-16 19:28:32 -0700 |
|---|---|---|
| committer | Jed Davis <jld@panix.com> | 2012-07-16 21:54:57 -0700 |
| commit | db34b5acd150d114f392c907fa28f92a5227d3db (patch) | |
| tree | e406028658b5d6aab6ce0afe337ec467ac4f3b14 /src/libcore | |
| parent | 0e42004babc7b965a10056084a8ae76c72140a44 (diff) | |
| download | rust-db34b5acd150d114f392c907fa28f92a5227d3db.tar.gz rust-db34b5acd150d114f392c907fa28f92a5227d3db.zip | |
Prevent random floats from occasionally being greater than 1.
Previously, gen_f64 could generate numbers as high as 1.0000000002328306 in the case that u3 was 4294967295.0f64 and u2 was nonzero. This change divides the random numbers by 2**32 instead, effectively concatenating their bits as apparently intended. (Bonus fix: const.) The comments are updated to be more specific than "random float"; note that this can still generate 1.0f64 (P = 2**-54) due to rounding.
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/rand.rs | 8 |
1 files changed, 4 insertions, 4 deletions
diff --git a/src/libcore/rand.rs b/src/libcore/rand.rs index 8d392e1be90..16979f7ad95 100644 --- a/src/libcore/rand.rs +++ b/src/libcore/rand.rs @@ -94,22 +94,22 @@ impl extensions for rng { (self.next() as u64 << 32) | self.next() as u64 } - /// Return a random float + /// Return a random float in the interval [0,1] fn gen_float() -> float { self.gen_f64() as float } - /// Return a random f32 + /// Return a random f32 in the interval [0,1] fn gen_f32() -> f32 { self.gen_f64() as f32 } - /// Return a random f64 + /// Return a random f64 in the interval [0,1] fn gen_f64() -> f64 { let u1 = self.next() as f64; let u2 = self.next() as f64; let u3 = self.next() as f64; - let scale = u32::max_value as f64; + const scale : f64 = (u32::max_value as f64) + 1.0f64; ret ((u1 / scale + u2) / scale + u3) / scale; } |
