I have a matlab piece of code that generates same random numbers (rand(n,1)
) when I initialize with rng('default');
Example:
>> rng('default');
>> rand(3,1)
ans =
0.8147
0.9058
0.1270
Now I need to generate the same output in Octave. Is there an equivalent function for rng('default')
in Octave? Please advise on how to get the same set of random numbers as MATLAB in Octave.
From the rand
documentation for Octave
By default, the generator is initialized from /dev/urandom if it is available, otherwise from CPU time, wall clock time, and the current fraction of a second. Note that this differs from MATLAB, which always initializes the state to the same state at startup. To obtain behavior comparable to MATLAB, initialize with a deterministic state vector in Octave’s startup files (see ‘Startup Files’).
To get around this difference, you will have to seed both the MATLAB and Octave random number generator, and specify the generation method, to try and ensure they're doing the same thing. Note I say "try" because fundamentally they're different languages and there is no equivalency guarantee.
However, it appears that MATLAB and Octave don't use equivalent seeds. User Markuman has provided an example on the Octave wiki to get around this
Octave
function ret = twister_seed(SEED=0)
ret = uint32(zeros(625,1));
ret(1) = SEED;
for N = 1:623
## initialize_generator
# bit-xor (right shift by 30 bits)
uint64(1812433253)*uint64(bitxor(ret(N),bitshift(ret(N),-30)))+N; # has to be uint64, otherwise in 4th iteration hit maximum of uint32!
ret(N+1) = uint32(bitand(ans,uint64(intmax('uint32')))); # untempered numbers
endfor
ret(end) = 1;
endfunction
octave:1> rand('twister',twister_seed) # notice: default seed is 0 in the function
octave:2> rand
ans = 0.548813503927325
octave:3> rand
ans = 0.715189366372419
octave:4> rand
ans = 0.602763376071644
MATLAB
>> rand('twister',0)
>> rand
ans =
0.548813503927325
>> rand
ans =
0.715189366372419
>> rand
ans =
0.602763376071644
So from the documentation quote at the top of this answer, you could set the random number generator seed during Octave startup if you want this behaviour by default.