0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
frankenapps
  • 5,800
  • 6
  • 28
  • 69
  • Uhm, `rand_chacha` should provide you with the sequence from a seed iirc. – Netwave May 12 '21 at 11:22
  • 4
    Basically, all the RNG structs in `rand_chacha` implement the `SeedableRng` trait, so you can call `ChaChaRng::from_seed()` or `ChaChaRng::from_seed_u64()` to initialize the RNG with a seed. – Sven Marnach May 12 '21 at 11:24

1 Answers1

3

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

Netwave
  • 40,134
  • 6
  • 50
  • 93