Random number not repeatable with the same seed
11 次查看(过去 30 天)
显示 更早的评论
Hi, I have a lengthy Matlab script for a stochastic simulation model. Every time I run a simulation, I initialize the random number generator at the top of the code by using
s = RandStream('mt19937ar','Seed',seedi);
RandStream.setGlobalStream(s);
I expect that I should get the same results as long as the value of seedi is the same, but it is not. I set the number of CPUs to 1
LASTN = maxNumCompThreads(1)
to avoid possible complications due to using multiple CPUs. But this did not solve the problem. Why is this happening? I also tried rng(seedi, 'twister') but it did not solve the problem, either. The script uses many matlab functions that use random numbers (randsample, gamrnd, poisoned, etc) for very numerous times. Is there any possibility that these functions might be resetting the seed somehow in the background? If so, how can I stop it? I need a consistent stream of random numbers for debugging.
0 个评论
回答(1 个)
Alessandro Masullo
2016-4-22
编辑:Alessandro Masullo
2016-4-22
The number of threads shouldn't affect your script, because matlab only use it internally. If you don't use a parfor or some tools of the parallel toolbox, you can safely leave the number of threads.
For getting always the same random number, using rng should be enough. Where is your "seedi" coming from? It may happen that something in your code is changing the rng, although none of the standard matlab functions do it, as far as I know.
Where did you set rng(seed,'twister')?
4 个评论
Alessandro Masullo
2016-4-26
Hi Etsuko,
I don't think there's any problem with the rng function. Maybe, you're setting some additional options in your code to generate different sizes of sets of random numbers. I remember that I had a similar problem with a Monte Carlo simulation, and in my case, the issue was related to my script.
I give you a very basic example; imagine that you have an iterative script that runs on random numbers:
rng(seed,'twister')
for i = 1:N_iter
input = rand(10);
output = sum(input(:));
end
Now, imagine that you want to compare two results of two different analysis, but one is based on N_iter = 3, the other on N_iter = 5. Since the rng is set at the beginning of the code, you won't be able to have a reliable comparison because the process of generating number is different (more iterations, in this case). Maybe in your case there's something similar.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!