3

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?

asked Dec 4, 2016 at 7:56
3
  • If you get something very close to zero, it is just floating point error Commented Dec 4, 2016 at 8:13
  • No I'm getting significant errors of the order of 10. Commented 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. Commented Dec 4, 2016 at 8:29

1 Answer 1

5

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.

answered Dec 4, 2016 at 8:49
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.