如何使用 Rust 中的 rand crate 输入整数种子来生成随机数?

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

在 Rust 项目中,我想根据我在 Java.

中习惯的整数种子生成 可重现的 随机数

rand 箱子中 Seed 的文档指出:

Seed type, which is restricted to types mutably-dereferencable as u8 arrays (we recommend [u8; N] for some N).

这是否意味着整数种子是不可能的?如果可能的话,我如何使用 StdRng 和完整的种子?

检查这个函数:StdRng::seed_from_u64

它来自 SeedableRng 特征,StdRng 实现了该特征。

例如:

let mut r = StdRng::seed_from_u64(42);

请注意,只要您在同一平台上使用相同的构建,这将为您提供可重现的随机数,但 StdRng 的内部实现不保证在平台和版本之间保持相同图书馆!如果平台和构建之间的可重复性对您很重要,那么请查看诸如 rand_chacharand_pcgrand_xoshiro.

之类的包

我将分享我自己的答案,因为我必须进行更多搜索才能实现我的目标。

Cargo.toml

[dependencies]
rand = "0.7.3"
rand_distr = "0.3.0"

代码:

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);
}

我的输出:

Normal Sample1: 12.75371699717887
Normal Sample2: 10.82577389791956
Random u8: 194
Random u16: 7290

作为michaelsrb mentioned on his 请注意,这将保证在您的(构建 - 平台)上的不同运行中具有相同的值,两个月后的版本中使用的相同种子可能会给出不同的值。