MATLAB: Does RAND return unexpected results in MATLAB 7.4 (R2007a)

MATLABmersennerandrandn

I am encountering unexpected results with the random number generator using RAND.
If I start a new session of MATLAB and execute:
rand
at the MATLAB command prompt, I do not receive the expected result: 0.95012928514718. This value corresponds to the default Marsaglia generator with an initial state of 0, corresponding to the initial default 35-word internal memory.

Best Answer

This enhancement has been incorporated in Release 2007a (R2007a). For previous product releases, read below for any possible workarounds:
The RAND function now uses the Mersenne Twister algorithm as default generator algorithm. This method generates double precision values in the closed interval [2^(-53), 1-2^(-53)], with a period of 2^19937-1. Prior to this release, MATLAB used an algorithm known as the Subtract-with-Borrow (SWB) algorithm.
RAND now produces different results than in previous releases. However, the results returned are still pseudorandom values drawn from a standard uniform distribution. Because the values returned by RAND are intended to be random, this change should not affect your code.
Compatibility Considerations
There are several things to keep in mind regarding this change:
  • If your code requires the exact values returned by rand in previous releases, you should use the statement
rand('state',0);
to reset RAND to use the SWB algorithm. The new default algorithm's internal state at startup is equivalent to using the statement
rand('twister',5489);
Note that the 'state' keyword corresponds specifically to the SWB algorithm; it cannot be used generally to refer to the internal state of the currently active algorithm.
  • Existing code that uses the 'state' keyword to reinitialize RAND in a statement such as
rand('state',sum(100*clock))
causes RAND to switch to using the SWB algorithm. You may want to use the 'twister' keyword, which resets RAND but does not switch algorithms.
  • Existing code that uses the 'state' keyword to save and restore the internal state of rand in statements such as
savedState = rand('state');
... % code that uses rand
rand('state',savedState);
may no longer work as intended. Specifically, the first line of code saves the state of the SWB generator algorithm (see the rand documentation for details).
If the default Mersenne Twister algorithm was the active one at that time, then using the saved state in the last line does not restore the RAND internal state to its original conditions. Instead, it switches the RAND algorithm to SWB. To save and restore the internal state of the Mersenne Twister algorithm, use the 'twister' keyword.
In addition to these compatibility considerations, changing the default random number generator avoids a defect in the former default method (SWB) that is mentioned in the following Bug Report: