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?
-
If you get something very close to zero, it is just floating point errornkjt– nkjt2016年12月04日 08:13:15 +00:00Commented Dec 4, 2016 at 8:13
-
No I'm getting significant errors of the order of 10.sixtyTonneAngel– sixtyTonneAngel2016年12月04日 08:28:18 +00:00Commented Dec 4, 2016 at 8:28
-
And if the random numbers produced are the same in r1 and r, I shouldn't even be getting floating point errors as they should be exactly the same.sixtyTonneAngel– sixtyTonneAngel2016年12月04日 08:29:29 +00:00Commented Dec 4, 2016 at 8:29
1 Answer 1
From the rng documentation:
sprev = rng(...)returns the previous settings of the random number generator used byrand,randi, andrandnbefore 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.