rust-random / rand

A Rust library for random number generation.
https://crates.io/crates/rand
Other
1.68k stars 430 forks source link

rand::SmallRng produces different values in WASM than Rust for the same seed #1310

Closed wilwade closed 1 year ago

wilwade commented 1 year ago

Threw together a quick repo that shows this difference: https://github.com/wilwade/wasm-rand-test

Expected: That the output is the same on both WASM and in Rust. Actual: It is different.

Might be something I am just missing?

pub fn test_random_values() -> Vec<u32> {
    // Create a SmallRng instance with a fixed seed.
    let mut rng = SmallRng::seed_from_u64(42);

    // Generate 10 random values.
    let mut wasm_values = Vec::new();
    for _ in 0..10 {
        wasm_values.push(rng.gen_range(1..100));
    }
    return wasm_values;
}
newpavlov commented 1 year ago

The SmallRng docs clearly state:

The current algorithm is Xoshiro256PlusPlus on 64-bit platforms and Xoshiro128PlusPlus on 32-bit platforms.

If you need portable reproducibility, you should use a concrete PRNG. We may change it in future and use the same PRNG on all targets (we had a discussion about it, but I can't find the link), but today it is what it is.

wilwade commented 1 year ago

Thanks. I guess I wasn't thinking of them as different bits (obvious in retrospect).

Curious about the choice, but thanks for the quick response.

dhardy commented 1 year ago

See also: https://rust-random.github.io/book/portability.html