sixtyTonneAngel
sixtyTonneAngel

Reputation: 901

MATLAB: Generate same Random Number sequence

I want to use the mersenne twister to generate 'N' random numbers between 10 to 50. I want to be able to generate the same sequence over and over again.

I wrote the following code: (seed = 50, a = 10, b = 50, N = number of required random numbers)

s = rng(seed, 'twister');
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

Now even I print

r1 - r

I don't get zero. I expect to get zero as I have reset the random number generator to it's initial state in the third line of my code.

My question is where am I going wrong?

Upvotes: 3

Views: 195

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

From the rng documentation:

sprev = rng(...) returns the previous settings of the random number generator used by rand, randi, and randn before changing the settings.

So your s is the previous state, not the set state. Changing things to

rng(seed, 'twister');
s=rng();
r = a + (b-a)*rand(N,1);
rng(s);
r1 = a + (b-a)*rand(N,1);

should produce the desired behavior.

This may seem cumbersome, but it arises since rng is meant to be treated like a toggle: you set your state while storing the previous one for future restoration. After all, immediately resetting the state appears to be more diagnostic than practical.

Upvotes: 5

Related Questions