How can I input an integer seed for producing random numbers using the rand crate in Rust?
Asked Answered
C

2

17

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?

Comma answered 24/11, 2019 at 18:1 Comment(1)
why the generated number should be the same even with the same "seed", Rust have its own implementation, java too.Parcae
H
19

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.

Hughmanick answered 24/11, 2019 at 18:56 Comment(0)
L
7

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.

Lacasse answered 4/12, 2020 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.