Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Dates
- using Random
- module Utils
- # Marsaglia Random Number Generator struct equivalent
- mutable struct MarsagliaRng
- q::Vector{UInt32}
- carry::UInt32
- mwc256_initialized::Bool
- mwc256_seed::Int32
- i::UInt8
- function MarsagliaRng(seed::Vector{UInt8})
- q = zeros(UInt32, 256)
- carry = 362436
- mwc256_initialized = false
- mwc256_seed = reinterpret(Int32, seed)[1]
- i = 255
- new(q, carry, mwc256_initialized, mwc256_seed, i)
- end
- end
- # Default constructor using system time for seeding
- function MarsagliaRng()
- ts_nano = UInt8(nanosecond(now()))
- seed = [ts_nano, ts_nano >>> 8, ts_nano >>> 16, ts_nano >>> 24]
- MarsagliaRng(seed)
- end
- # Random number generator functions
- function next_u32(rng::MarsagliaRng)::UInt32
- a = UInt64(809430660)
- if !rng.mwc256_initialized
- j = UInt32(rng.mwc256_seed)
- c1 = UInt32(69069)
- c2 = UInt32(12345)
- rng.mwc256_initialized = true
- for k in 1:256
- j = (c1 * j + c2) % UInt32
- rng.q[k] = j
- end
- end
- rng.i = (rng.i + 1) % 256
- t = a * UInt64(rng.q[rng.i+1]) + UInt64(rng.carry)
- rng.carry = (t >> 32)
- rng.q[rng.i+1] = t % UInt32
- return rng.q[rng.i+1]
- end
- function next_u64(rng::MarsagliaRng)::UInt64
- UInt64(next_u32(rng))
- end
- # Sample function for generating a Float64
- function rand(rng::MarsagliaRng)::Float64
- mult = 1.0 / typemax(UInt32)
- mult * next_u32(rng)
- end
- export MarsagliaRg, next_u32, rand
- end
Advertisement
Add Comment
Please, Sign In to add comment