【问题标题】:get same results in every simulation with matlab [duplicate]使用matlab在每次模拟中获得相同的结果[重复]
【发布时间】:2012-09-08 00:42:00
【问题描述】:

可能重复:
How to set custom seed for pseudo-random number generator

我正在使用 matlab 构建一些模拟,并使用 rand 函数。

我想在每次运行时都获得相同的结果。我在某处读到我必须设置 rand 函数的种子。我尝试使用

s = RandStream('mcg16807', 'seed', 0)
RandStream.setGlobalStream(s);

但它没有用。我是不是搞错了?

>> s = RandStream('mcg16807', 'seed', 5)
>> RandStream.setGlobalStream(s);
>> rand

ans = 

    0.5645

>> rand
ans = 

    0.3024

>> rand
ans = 

    0.7520

【问题讨论】:

  • 检查here
  • @angainor 我已经阅读了那篇文章,但它没有用
  • 你写的东西对我来说很完美。我不知道你还需要什么。调用这两行代码后,rand 返回相同的数字。
  • 如果你想得到相同的结果,你必须在每个rand之前再次执行RandStream
  • 当然。每次 after 为生成器播种时,它都会从同一点开始生成序列。这并不意味着它只会生成一个数字。这将是相同的数字序列。

标签: matlab random simulation random-seed


【解决方案1】:

当您想重新开始并获得相同的随机数集时,您必须调用RandStream.setGlobalStream

>> s = RandStream('mcg16807', 'seed', 5)
>> RandStream.setGlobalStream(s);
>> rand

ans = 

    0.5645

>> rand
ans = 

    0.3024

>> s = RandStream('mcg16807', 'seed', 5)
>> RandStream.setGlobalStream(s);
>> rand

ans = 

    0.5645

>> rand
ans = 

    0.3024

我通常只调用一次setGlobalStream,在我想每次都给我相同答案的脚本开头。 rand抽到的数字都是随机的,但每次都是同一组随机数。

【讨论】:

  • 但是如果在我的脚本中我有一个 for 循环并且在每个循环中我调用 rand 函数,那么我必须在每个循环中调用 setGlobalStream 来获得相同的值吗?
  • 从技术上讲,这是可行的。但是,最好将rand 的结果简单地保存在循环外的变量中,然后在 for 循环内使用该变量。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
相关资源
最近更新 更多