Skip to content

Commit

Permalink
Make MersenneTwister equivalent in 32- and 64-bit architectures
Browse files Browse the repository at this point in the history
As mentioned in issue JuliaLang#5999, reproduce the solution in 67f6fee for the MersenneTwister.

Note that users on 64-bit architectures will see their randomness change with no change in their seed.
  • Loading branch information
Joseph Perla committed Mar 2, 2014
1 parent d2d257b commit edb5c01
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
17 changes: 3 additions & 14 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,15 @@ type MersenneTwister <: AbstractRNG
state::DSFMT_state
seed::Union(Uint32,Vector{Uint32})

function MersenneTwister()
seed = uint32(0)
state = DSFMT_state()
dsfmt_init_gen_rand(state, seed)
return new(state, seed)
end

function MersenneTwister(seed::Uint32)
state = DSFMT_state()
dsfmt_init_gen_rand(state, seed)
return new(state, seed)
end

function MersenneTwister(seed::Vector{Uint32})
state = DSFMT_state()
dsfmt_init_by_array(state, seed)
return new(state, seed)
end

MersenneTwister(seed) = MersenneTwister(reinterpret(Uint32, [seed]))
MersenneTwister() = MersenneTwister(make_seed(uint32(0)))
MersenneTwister(seed::Uint32) = MersenneTwister(make_seed(seed))
MersenneTwister(seed) = MersenneTwister(make_seed(seed))
end

function srand(r::MersenneTwister, seed)
Expand Down
6 changes: 6 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@
@test length(randn(4, 5)) == 20
@test length(randbool(4, 5)) == 20

@test (rand(MersenneTwister()) - 0.8236475079774124) < 0.01
@test (rand(MersenneTwister(0)) - 0.8236475079774124) < 0.01
@test (rand(MersenneTwister(42)) - 0.5331830160438613) < 0.01
# Try a seed larger than 2^32
@test (rand(MersenneTwister(5294967296)) - 0.3498809918210497) < 0.01

for T in (Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Int128, Uint128, Char, BigInt,
Float16, Float32, Float64, Rational{Int})
r = rand(convert(T, 97):convert(T, 122))
Expand Down

0 comments on commit edb5c01

Please sign in to comment.