我需要执行一些测试,其中我使用randn
伪随机数生成器。我怎样才能自己设置种子,所以每次运行这个测试我都会得到相同的结果? (是的,我知道这有点奇怪,但那就是问题)。
我找到了具有RANDSTREAM
属性的seed
对象,但它是只读的。有没有办法用它来播种发电机?
答案 0 :(得分:24)
旧方法:
randn('seed',0)
新方式:
s = RandStream('mcg16807','Seed',0)
RandStream.setDefaultStream(s)
请注意,如果您使用新方式,rand
和randn
共享同一个流,那么如果您同时调用这两个流,您可能会发现与旧方法相比生成的数字不同(具有单独的方法)发电机)。由于这个原因(和遗留代码)仍然支持旧方法。
有关详细信息,请参阅http://www.mathworks.com/help/techdoc/math/bsn94u0-1.html。
答案 1 :(得分:9)
您可以调用rng(mySeed)
来设置全局流的种子(在Matlab R2011b中测试)。这会影响rand
,randn
和randi
函数。
same page that James linked to将此列为各种旧方法的推荐替代方法(请参阅表格右栏的中间单元格)。
以下是一些示例代码:
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]));
它的输出是:
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
答案 2 :(得分:2)
mySeed=57; % an integer number
rng(mySeed,'twister') %You can replace 'twister' with other generators
答案 3 :(得分:0)
当您只想将RNG重置为某种已知状态时,只需使用:
seed = 0;
randn('state', seed);
rand ('state', seed);
A = round(10*(rand(1,5))); // always will be [10 2 6 5 9]