分布中的种子rng。
我有一个具有功能的模块,我需要确保所有功能都使用相同的随机值。我目前有两个解决方案,在每个调用中重置种子:
using Distributions
function random_values(n)
Random.seed!(1)
rand(Normal(), n)
end
或类似地,直接实例化:
using Distributions
function random_values(n)
rand(MersenneTwister(1), Normal(), n)
end
这有效,但我有多个功能,并且代码变为冗长。我宁愿将种子设置为模块级别,以便所有功能都使用相同。我该怎么能最好地实现这一目标?
I have a module with functions where I need to ensure that all functions use the same random values. I currently have two solutions, resetting the seed at each call:
using Distributions
function random_values(n)
Random.seed!(1)
rand(Normal(), n)
end
or similarly, instantiating it directly:
using Distributions
function random_values(n)
rand(MersenneTwister(1), Normal(), n)
end
This works but I have several functions and the code becomes a bit verbose. I would rather set a seed at the module level so that all functions use the same. How can I best achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您想要的是每个调用rand()两个或多个函数(F1,F2,...)。您希望它们在“同步”中,以便使用一系列函数调用每个函数每个函数的每个顺序调用都相同的值(因此,对F2的第三个调用使用相同的rand()值与第三个调用对F1)。
为此,最好在将每个功能初始化到同一种子之后明确将重复的RNG对象转移到每个功能:
然后将与此相关,
这确实意味着编码更多,因为您在每个函数中添加了一个参数,但是灵活性,但是并且最初的额外编码可重复可重复可重现您的蒙特卡洛方法时,在编码其余的工作时,可能会使您非常有价值。
I believe that what you want is to have two or more functions (f1, f2, ...) that each call rand(). You want them in "sync" so that with a series of function calls each function gets the same series of values for each sequential call of each function (so that the third call to f2 uses the same rand() value as the third call to f1).
For this, you are best off explicitly passing a duplicated RNG object to each of your functions after initializing each to the same seed:
will then be in sync with
This does mean more coding since you add one more argument to each function, but the flexibility and reproducibility that initial extra coding gives you with your Monte Carlo methods when coding the rest of what you do may make it very worthwhile.