Repository navigation
Description
The output of Rng::gen_range is different depending on whether usize is 32 bits or 64 bits on the current platform, even if the requested range is small (0..12 in my case). For example:
use rand::Rng;
use rand_core::SeedableRng;
let mut rng = rand_pcg::Pcg32::seed_from_u64(0);
for _ in 0..16 {
let x: usize = rng.gen_range(0..12);
print!("{} ", x);
}
println!();
On a 64-bits system, the output is: 4 8 6 0 5 1 5 8 9 10 11 7 6 11 1 8
On a 32-bits system, the output is: 4 1 8 0 6 1 0 8 5 11 1 9 5 5 8 6
This does not affect SliceRandom::choose, thanks to some special handling in gen_index:
Lines 699 to 710 in 7ff0fc9
| // Sample a number uniformly between 0 and `ubound`. Uses 32-bit sampling where | |
| // possible, primarily in order to produce the same output on 32-bit and 64-bit | |
| // platforms. | |
| #[inline] | |
| fn gen_index<R: Rng + ?Sized>(rng: &mut R, ubound: usize) -> usize { | |
| if ubound <= (core::u32::MAX as usize) { | |
| rng.gen_range(0..ubound as u32) as usize | |
| } else { | |
| rng.gen_range(0..ubound) | |
| } | |
| } |
This means that, contrary to my expectations, my_slice.choose(&mut rng) and my_slice[rng.gen_range(0..my_slice.len())] are not equivalent (even ignoring the case of an empty slice).
I'm not sure if this qualifies as a bug, but it definitely surprised me, and took me some time to debug. I'm also not sure if it can be fixed, and if fixing it would constitute a breaking change.
In any case it could be documented, here in the book and here on Rng::gen_range.
Activity
dhardy commentedon Feb 20, 2024
We could add
gen_indexto theRngtrait and improve docs (by mentioning ingen_range).Should we, in this case, make
Rng::gen_indexaccept a range likeRng::gen_range?We could go further and remove support for
usizefromStandardandgen_range, requiring usage of a special method likegen_indexor casting... this would be quite disruptive.vks commentedon Mar 21, 2024
For this use case, we could also change
gen_rangeto generate au32the range is small enough (for any integer type). This would make generatingusizeportable without adding more API surface.newpavlov commentedon Mar 21, 2024
What about 16 bit targets? Would they generate
u32as well?vks commentedon Mar 22, 2024
Yes, we only have
RngCore::next_u64andRngCore::next_u32. The portability issue arises, because 64-bit platforms usenext_u64to generateusize, while 32-bit platforms usenext_u32. If both usednext_u32, the problem would be fixed. (For large ranges we would still have to usenext_u64on 64-bit platforms, but they would not fit into a 32-bitusizeanyway.)dhardy commentedon Mar 22, 2024
Similar, recent issues: #1373 #1415. Also, discussions by rand developers: comment in #1196, #809, #805. We should consider this again.
To be precise, there are two issues:
rng.gen_range(0..my_slice.len()), there is a hidden portability hazard.my_slice.choose(&mut rng)andmy_slice[rng.gen_range(0..my_slice.len())]are not equivalent.Solutions
Document the portability hazard
In the book: Portability of usize
We could document this hazard in more places, especially on
Rng::gen_range.Test the range
We use this internal method for
choose, added in #809:This is an extra conditional-jump on 64-bit platforms, but one which almost always resolves to the first branch in practice, and thus likely has a little cost in most cases.
We could use this approach also for the impl of
Uniform(gen_range) forusizeandisize.Above + remove non-portable
StandardimplsThe leaves non-portable behaviour, which could be resolved by additionally removing
usizeandisizeimpls fromStandard.Note:
sample_single_inclusive(0, usize::MAX, rng)should probably optimise down suitably as an alternative. This is still not great for anyone wanting a generic solution, but it's really hard to imagine why anyone would actually want that given thatusizeis used for sizes which are never uniformly distributed over allusizevalues (this even applies to offsets, unless your memory size is exactlyusize::MAX + 1bytes).Remove all non-portable impls from
StandardandUniformWe implement equivalent code to the above, but not under the
UniformSamplertrait. Instead ofRng::gen_range, people must useRng::gen_index.This is more disruptive and less generic friendly than the above, for no obvious benefit.
dhardy commentedon Jul 12, 2024
Locations where non-portable generation of
usize/isizevalues occurs:impl rand::Fill for [usize]and for[isize]rand::seq::index::sample_array(new code)rand::distributions::Slice::sampleimpl rand::distributions::Distribution<usize> for Standard, also forisizeimpl Distribution<Simd<usize, LANES>> for Standard, also forisizerand::distributions::UniformSamplerWideningMultiply for usize; non-random and used byUniform)As a lesser form of non-portability, the following support
usizevalues larger thanu32::MAXbut remain portable with 32-bitusizefor smaller values:rand::seq::index::sampleFrom the above,
sample_arrayandSlice::sampleshould probably be made portable (likeindex::samplealready is).Non-portable wrapper
We could add a wrapper type,
rand::Nonportable(orUnportable?), and implementFill,DistributionandUniformSamplerover this wrapper for all supported un-wrapped types and support wrappedusize,isizevalues.We can then remove support for generating unwrapped
isize,usizevalues, and addRng::gen_index(repackaging of the private functionseq::gen_index) for convenience.dhardy commentedon Jul 26, 2024
FYI I'm strongly considering removing all support for random
usize/isizevalues in #1471, except:Rng::gen_indexhelperUniformUsizewhich uses range-specificu32oru64sampling?We could even release this, then add sampling back later if there is a significant demand — though I'd prefer not to, since this is non-portable behaviour, and any case where random
usizeorisizevalues are required probably requires special attention (the obvious exception beinggen_index).vks commentedon Jul 26, 2024
Couldn't we make it portable (by using
gen_index) instead of removing it? This would cause less breakage and seems more user-friendly.dhardy commentedon Jul 26, 2024
We could do. There's already
UniformUsizeinrand::distr::slice(private); I started making that public and more flexible, but then wasn't sure whether to go that route.dhardy commentedon Aug 10, 2024
Small update: #1471 and
alpha.2have portableRng::gen_rangeforusizeand portableRng::gen_indexforusize; we probably won't be keeping both.dhardy commentedon Sep 13, 2024
Changed in #1487.