rand: make mt19937 automatically seeded, add seed_len to wyrand (#13966)

pull/13969/head
Subhomoy Haldar 2022-04-07 18:30:30 +05:30 committed by GitHub
parent 95753ffb30
commit 022fae1e7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 3 deletions

View File

@ -3,6 +3,8 @@
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module mt19937 module mt19937
import rand.seed
/* /*
C++ functions for MT19937, with initialization improved 2002/2/10. C++ functions for MT19937, with initialization improved 2002/2/10.
Coded by Takuji Nishimura and Makoto Matsumoto. Coded by Takuji Nishimura and Makoto Matsumoto.
@ -59,12 +61,18 @@ const (
// **NOTE**: The RNG is not seeded when instantiated so remember to seed it before use. // **NOTE**: The RNG is not seeded when instantiated so remember to seed it before use.
pub struct MT19937RNG { pub struct MT19937RNG {
mut: mut:
state []u64 = []u64{len: mt19937.nn} state []u64 = get_first_state(seed.time_seed_array(2))
mti int = mt19937.nn mti int = mt19937.nn
bytes_left int bytes_left int
buffer u64 buffer u64
} }
fn get_first_state(seed_data []u32) []u64 {
mut state := []u64{len: mt19937.nn}
calculate_state(seed_data, mut state)
return state
}
// calculate_state returns a random state array calculated from the `seed_data`. // calculate_state returns a random state array calculated from the `seed_data`.
fn calculate_state(seed_data []u32, mut state []u64) []u64 { fn calculate_state(seed_data []u32, mut state []u64) []u64 {
lo := u64(seed_data[0]) lo := u64(seed_data[0])
@ -83,8 +91,6 @@ pub fn (mut rng MT19937RNG) seed(seed_data []u32) {
eprintln('mt19937 needs only two 32bit integers as seed: [lower, higher]') eprintln('mt19937 needs only two 32bit integers as seed: [lower, higher]')
exit(1) exit(1)
} }
// calculate 2 times because MT19937RNG init didn't call calculate_state.
rng.state = calculate_state(seed_data, mut rng.state)
rng.state = calculate_state(seed_data, mut rng.state) rng.state = calculate_state(seed_data, mut rng.state)
rng.mti = mt19937.nn rng.mti = mt19937.nn
rng.bytes_left = 0 rng.bytes_left = 0

View File

@ -12,6 +12,8 @@ const (
wyp1 = u64(0xe7037ed1a0b428db) wyp1 = u64(0xe7037ed1a0b428db)
) )
pub const seed_len = 2
// WyRandRNG is a RNG based on the WyHash hashing algorithm. // WyRandRNG is a RNG based on the WyHash hashing algorithm.
pub struct WyRandRNG { pub struct WyRandRNG {
mut: mut: