I need to perform few tests where I use randn
pseudo random number generator. How can I set th开发者_如何学Goe seed on my own, so every time I run this test I will get the same results? (yeah, I know it's a little bit weird, but that's the problem).
I've found the RANDSTREAM
object that has the seed
property, but it's read only. Is there any way to use it for seeding the generator?
The old way of doing it:
randn('seed',0)
The new way:
s = RandStream('mcg16807','Seed',0)
RandStream.setDefaultStream(s)
Note that if you use the new way, rand
and randn
share the same stream so if you are calling both, you may find different numbers being generated compared to the old method (which has separate generators). The old method is still supported for this reason (and legacy code).
See http://www.mathworks.com/help/techdoc/math/bsn94u0-1.html for more info.
You can just call rng(mySeed)
to set the seed for the global stream (tested in Matlab R2011b). This affects the rand
, randn
, and randi
functions.
The same page that James linked to lists this as the recommended alternative to various old methods (see the middle cell of the right column of the table).
Here's some example code:
format long; % Display numbers with full precision format compact; % Get rid of blank lines between output mySeed = 10; rng(mySeed); % Set the seed disp(rand([1,3])); disp(randi(10,[1,10])); disp(randn([1,3])); disp(' '); rng(mySeed); % Set the seed again to duplicate the results disp(rand([1,3])); disp(randi(10,[1,10])); disp(randn([1,3]));
Its output is:
0.771320643266746 0.020751949359402 0.633648234926275 8 5 3 2 8 2 1 7 10 1 0.060379730526407 0.622213879877005 0.109700311365407 0.771320643266746 0.020751949359402 0.633648234926275 8 5 3 2 8 2 1 7 10 1 0.060379730526407 0.622213879877005 0.109700311365407
mySeed=57; % an integer number
rng(mySeed,'twister') %You can replace 'twister' with other generators
When you just want to reset the RNG to some known state, just use:
seed = 0;
randn('state', seed);
rand ('state', seed);
A = round(10*(rand(1,5))); // always will be [10 2 6 5 9]
精彩评论