How to set custom seed for pseudo-random number generator

后端 未结 4 1894
后悔当初
后悔当初 2020-11-30 09:38

I need to perform few tests where I use randn pseudo random number generator. How can I set the seed on my own, so every time I run this test I will get the sam

相关标签:
4条回答
  • 2020-11-30 10:13
    mySeed=57; % an integer number
    rng(mySeed,'twister') %You can replace 'twister' with other generators
    
    0 讨论(0)
  • 2020-11-30 10:20

    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.

    0 讨论(0)
  • 2020-11-30 10:24

    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
    
    0 讨论(0)
  • 2020-11-30 10:37

    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]
    
    0 讨论(0)
提交回复
热议问题