roov
roov

Reputation: 33

Are numbers generated by rand() in matlab dependent?

I have a question about rand() in MATLAB.

I want to know whether the numbers generated by rand() are dependent.

For example, I generate directly a 1*2 matrix N by rand().

Will N(1) influence the N(2)? If N(1) is 0.2, then N(2) will greater or less than 0.2 with higher probability?

Upvotes: 0

Views: 150

Answers (1)

Roland Smith
Roland Smith

Reputation: 43505

Absent special hardware, computers cannot really generate random numbers. They use algorithms to generate pseudorandom numbers these are called pseudorandom number generators ("PRNG").

In the case of matlab, it uses the Mersenne Twister as its default generator. The linked Wikipedia entry sums up the strengths and weeknesses of the Mersenne Twister nicely.

Because of the way a PRNG works, subsequent outputs of a PRNG are dependent. Or as James Polk suggested, it is more accurate to say that subsequent values depend on the internal state, which changes in a deterministic way with every call.

If you re-seed a PRNG with the same value, it will produce the same sequence of numbers as before. See the example below in Python (which also uses the Mersenne Twister).

In [1]: import random                                                                                    

In [2]: random.seed('foobar')                                                                            

In [3]: [random.randint(0, 255) for j in range(15)]                                                      
Out[3]: [128, 127, 178, 80, 112, 31, 1, 234, 24, 206, 253, 213, 6, 215, 16]

In [4]: random.seed('foobar')                                                                            

In [5]: [random.randint(0, 255) for j in range(15)]                                                      
Out[5]: [128, 127, 178, 80, 112, 31, 1, 234, 24, 206, 253, 213, 6, 215, 16]

And eventually the sequence will repeat itself. This is called the "period" of the PRNG.

If this PRNG has just been started it can take a while before it produces output of a good randomness because of the large internal state. You'd have to run tests to see if that is the case in matlab. It could be that the matlab developers have dealt with this be generating and discarding a significant amount of random numbers when initializing the generator.

To test this, generate several 1 kiB blocks of random bytes using matlab. Then use e.g dieharder or ent to check and compare the randomness of the subsequent blocks.

Upvotes: 4

Related Questions