frankenapps
frankenapps

Reputation: 8241

How to produce reproducible pseudo-random numbers based on a seed for all platforms with the rand crate?

This is a follow-up to How can I input an integer seed for producing random numbers using the rand crate in Rust?. In this answer, it is stated that if reproducibility across builds and architectures is desired,

then look at crates such as rand_chacha, rand_pcg, rand_xoshiro

The same is stated in the documentation for StdRng:

The algorithm is deterministic but should not be considered reproducible due to dependence on configuration and possible replacement in future library versions. For a secure reproducible generator, we recommend use of the rand_chacha crate directly.

I have looked at these crates, but I have not found out how to use them for my use case. I am looking for a small sample showing how one of these crates can be used for generating a sequence of pseudo-random numbers, that are always the same for a given seed.

Upvotes: 0

Views: 1757

Answers (1)

Netwave
Netwave

Reputation: 42688

An example using rand_chacha::ChaCha8Rng:

use rand_chacha::rand_core::SeedableRng;
use rand_core::RngCore;
use rand_chacha; // 0.3.0

fn main() {
    let mut gen = rand_chacha::ChaCha8Rng::seed_from_u64(10);
    let res: Vec<u64> = (0..100).map(|_| gen.next_u64()).collect(); 
    println!("{:?}", res);
}

Playground

Upvotes: 4

Related Questions