# How can I generate the same random number in Mathematica and MATLAB?

As a part of my research studies, I have developed a code which is essentially based on random generation of numbers. The first version of the code was written in MATLAB, however, for some reasons I transferred it to Mathematica for further development. In order to assure the correctness of my code in Mathematica, I decided to compare the corresponding results with those from MATLAB. It happened that I was not able to carry out my comparison quantitatively, as I couldn't tweak the random number generators to give the same quantities.

As written in the Mathematica documentation, the possible random number generation methods are as follows: On the other hand, the MATLAB documentation reads So as it appears, the Mersenne Twister is the only common algorithm between MATLAB and Mathematica, but, as shown below, it does not generate the same number in the two environments.  What is the reason for this?

• You'll probably have to write your own PRNGs. Implementation details matter, and that's only under you control if you do the coding yourself. Fortunately, PRNG algorithms aren't terribly complicated. If you don't need great quality, something as simple as a linear congruential generator (en.wikipedia.org/wiki/Linear_congruential_generator) may work fine. Lagged Fibonacci generators (en.wikipedia.org/wiki/Lagged_Fibonacci_generator) are better, fast, and also pretty easy to code. Sep 26, 2021 at 13:38
• Perhaps you could call Matlab through Mathematica directly? matlink.org Sep 26, 2021 at 13:39
• Related: 184614. Sep 26, 2021 at 14:27
• Maybe just write the rng-numbers from matlab into a file and load it in Mathematica to sample from it. Sep 26, 2021 at 15:07
• @JulienKluge Unfortunately I want to run a complementary process in Mathematica to one that is in MATLAB and I need to match random number generation to do so. Sep 26, 2021 at 16:31

If it is solely for regression testing, the quality of the random numbers doesn't matter very much. You can substitute a better random number generator once you know the Mathematica version matches the MATLAB version.

In which case, you might use something like

Mathematica

Module[{seed = 123456789},
random := With[{a = 69069, b = 1},
seed = Mod[a seed + b, 2^32];
N[seed/2^32]
]
]

Table[random, {5}]
(* {0.355504, 0.286935, 0.320493, 0.135751,0.213987} *)


Octave

function u = Random
persistent seed
if isempty(seed)
seed = uint64(123456789);
end

a = uint64(69069);
b = uint64(1);
seed = mod(a * seed + b, 2^32);
u = (2^-32) * double(seed);
end

Octave:> [Random, Random, Random, Random, Random]
ans =

0.35550   0.28694   0.32049   0.13575   0.21399