How to set custom seed for pseudo-random number generator

后端 未结 4 1898
后悔当初
后悔当初 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: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
    

提交回复
热议问题