Random bits in rug crate always the same

This is probably a beginner's mistake, but I can't figure it out. I want to create random bits using the rug crate, but keep getting the same bits (within and across executions).

The following code (taken from the documentation)

use rug::rand::RandState;

fn main() {
    for _i in 0..5 {
	   let mut rand = RandState::new();
	   let u = rand.bits(32);
	   println!("32 random bits: {:032b}", u);
    }
}

gives me this every time:

32 random bits: 00111001101111001010100001110100
32 random bits: 00111001101111001010100001110100
32 random bits: 00111001101111001010100001110100
32 random bits: 00111001101111001010100001110100
32 random bits: 00111001101111001010100001110100

My Cargo.toml just has this as a dependency:

[dependencies]
rug = "1.16"

Can someone tell me what I'm missing?

PRNGs are deterministic algorithms, so usually, it's necessary to seed them with different values if you expect to get a different set of random outputs.

Note that the documentation does not say that you should re-create the state inside the loop upon every single iteration. PRNGs aren't supposed to be used like that.

The whole reason why a PRNG is an object and not a simple function is that it has state, so it can generate different values upon each invocation. You should thus create the object once, outside the loop, and only call the generating function inside the loop body.

3 Likes

Thank you for the explanation! That indeed leads to different bits throughout the loop. And for getting different bits across executions the important thing I didn't realize is that the rug PRNG needs to be seeded, which, for future reference, can be done with the seed method. Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.