Randn isn't consistent with Seed?

When I run the following few lines of code, I get the attached behavior where the first few elements of using randn will be the same but after a while (not sure if machine dependent) the same rng will diverge, but only with randn as rand works as expected. Just wanted to ask here if folks had an explanation or any idea why this occurs.

using Random
r1 = MersenneTwister(1)
r2 = MersenneTwister(1)

N = 20
a = [ randn(r1) for i=1:N ] # there seems to be a difference in batch calling randn vs sequentially
b = randn(r2, N)

julia> a-b
20-element Vector{Float64}:
  0.0
  0.0
  0.0
  0.0
  0.0
  0.0
  0.0
 -1.5094533110800028
  0.3009560212569654
  2.698507875223443
  0.05374271140203246
  0.5318500786152787
 -0.12491733251506171
 -1.4856083624596992
 -0.05039511672896463
  0.4718855274878431
 -1.102049482128638
 -1.7233820234743904
  0.8144196087413249
  1.0162002156875278

@rfourquet Pinging you as our native Random expert.

1 Like

I think this is from faster randn!(::MersenneTwister, ::Array{Float64}) by rfourquet · Pull Request #35078 · JuliaLang/julia · GitHub.

Yeah, that must be it. I suspected that it was some optimization for batch producing the randoms, but was really scratching my head. It seems a little bit breaking that they don’t produce the same sequence since N randn values should be the same with the same seed, but if people know about this then they can avoid it.

Thanks all!

Note that the same behavior exists also with rand, for a bigger N.

Very good to know, thanks!

See also Weird PRNG behavior