Skip to content

Commit 29329c9

Browse files
committed
Suggest gen_range as alternative for [0, 1)
1 parent 73ea10f commit 29329c9

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/distributions/mod.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ impl<'a, T, D: Distribution<T>> Distribution<T> for &'a D {
248248
/// let mut rng = thread_rng();
249249
/// let erased_rng: &mut RngCore = &mut rng;
250250
/// let val: f32 = erased_rng.sample(Standard);
251-
/// println!("f32 from (0,1): {}", val);
251+
/// println!("f32 from (0, 1): {}", val);
252252
/// ```
253253
///
254254
/// # Open interval for floats
@@ -271,6 +271,17 @@ impl<'a, T, D: Distribution<T>> Distribution<T> for &'a D {
271271
/// than the guarantee some value (`0.0`) is never generated. That makes an open
272272
/// interval a nicer choice.
273273
///
274+
/// Consider using `Rng::gen_range` if you really need a half-open interval (as
275+
/// the ranges use a half-open interval). It has the same performance. Example:
276+
///
277+
/// ```
278+
/// use rand::{thread_rng, Rng};
279+
///
280+
/// let mut rng = thread_rng();
281+
/// let val = rng.gen_range(0.0f32, 1.0);
282+
/// println!("f32 from [0, 1): {}", val);
283+
/// ```
284+
///
274285
/// [`Exp1`]: struct.Exp1.html
275286
/// [`StandardNormal`]: struct.StandardNormal.html
276287
#[derive(Debug)]

src/distributions/range.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,8 @@ macro_rules! range_int_impl {
287287
}
288288

289289
fn sample_single<R: Rng + ?Sized>(low: Self::X,
290-
high: Self::X,
291-
rng: &mut R) -> Self::X
290+
high: Self::X,
291+
rng: &mut R) -> Self::X
292292
{
293293
let range = (high as $u_large)
294294
.wrapping_sub(low as $u_large);
@@ -458,6 +458,19 @@ macro_rules! range_float_impl {
458458
// use a single instruction.
459459
value1_2 * self.scale + self.offset
460460
}
461+
462+
fn sample_single<R: Rng + ?Sized>(low: Self::X,
463+
high: Self::X,
464+
rng: &mut R) -> Self::X {
465+
let scale = high - low;
466+
let offset = low - scale;
467+
// Generate a value in the range [1, 2)
468+
let value1_2 = (rng.$next_u() >> $bits_to_discard)
469+
.into_float_with_exponent(0);
470+
// Doing multiply before addition allows some architectures to
471+
// use a single instruction.
472+
value1_2 * scale + offset
473+
}
461474
}
462475
}
463476
}

0 commit comments

Comments
 (0)