In a Rust project, I want to generate reproducible random numbers based on a integer seed as I'm used to in Java.
The documentation for Seed
in the rand
crate states:
Seed type, which is restricted to types mutably-dereferencable as u8 arrays (we recommend [u8; N] for some N).
Does this mean an integer seed is not possible? If it is possible, how can I use StdRng
with an integral seed?
Check this function out: StdRng::seed_from_u64
It comes from the SeedableRng
trait, which StdRng
implements.
For example:
let mut r = StdRng::seed_from_u64(42);
Note that this will give you reproducible random numbers as long as you use the same build on the same platform, but the internal implementation of the StdRng
is not guaranteed to stay the same between platforms and versions of the library! If reproducibility between platforms and builds is important for you, then look at crates such as rand_chacha
, rand_pcg
, rand_xoshiro
.
I will share my own answer because I had to search a little more to achieve my goal.
Cargo.toml
[dependencies]
rand = "0.7.3"
rand_distr = "0.3.0"
Code:
use rand_distr::{Normal, Distribution};
use rand::{Rng,SeedableRng};
use rand::rngs::StdRng;
fn main() {
let mut r = StdRng::seed_from_u64(222); // <- Here we set the seed
let normal = Normal::new(15.0, 5.0).unwrap(); //<- I needed Normal Standard distribution
let v1 = normal.sample(&mut r); // <- Here we use the generator
let v2 = normal.sample(&mut r);
let n1: u8 = r.gen(); // <- Here we use the generator as uniform distribution
let n2: u16 = r.gen();
println!("Normal Sample1: {}", v1);
println!("Normal Sample2: {}", v2);
println!("Random u8: {}", n1);
println!("Random u16: {}", n2);
}
My Output:
Normal Sample1: 12.75371699717887
Normal Sample2: 10.82577389791956
Random u8: 194
Random u16: 7290
As michaelsrb mentioned on his answer Please note that this will guarantee the same values on different runs on your (build - Platform), the same seed used in a two months later version, could give different values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With