gpt4 book ai didi

python - 在模拟中实现常见的随机数

转载 作者:太空狗 更新时间:2023-10-29 17:08:40 24 4
gpt4 key购买 nike

我正在用 Python 构建一个小型模拟,我想使​​用 Common Random Numbers以减少变异。我知道我必须实现同步才能使 CRN 工作:

CRN requires synchronization of the random number streams, which ensures that in addition to using the same random numbers to simulate all configurations, a specific random number used for a specific purpose in one configuration is used for exactly the same purpose in all other configurations.

我想知道我想在我的模拟中实现它的方式是否有效,或者我是否应该使用不同的方法。

我的模拟具有三个不同的类别(A 类、B 类、C 类),A 类对象具有随机旅行时间,B 类对象具有随机服务时间和随机使用率,C 类对象具有随机服务时间。当然,每一类对象可以有多个实例。

在模拟开始时,我指定了一个随机数种子 (replication_seed),这样我就可以为每个模拟复制使用不同的种子。

import numpy.random as npr
rep_rnd_strm = npr.RandomState().seed(replication_seed)

然后在每个类的构造函数中,我使用 rep_rnd_strm 生成用于初始化类实例的随机数流的种子:

self.class_rnd_strm = npr.RandomState().seed(rep_rnd_strm.randint(10000000))

然后我使用 self.class_rnd_strm 为类实例所需的每个随机数流生成一个种子。例如 ClassA 的构造函数有:

self.travel_time_strm = npr.RandomState().seed(self.class_rnd_strm.randint(10000000))

而 ClassB 的构造函数有:

self.service_time_strm = npr.RandomState().seed(self.class_rnd_strm.randint(10000000))
self.usage_rate_strm = npr.RandomState().seed(self.class_rnd_strm.randint(10000000))

我在这里所做的是使同步工作的有效方法,还是我应该以不同的方式做事?

最佳答案

是的。这是使其可复制的有效方法,但前提是您可以保证各个类的各个实例的实例化顺序没有随机性。这是因为如果它们以不同的顺序实例化,那么它们的随机数生成器将获得不同的种子。

关于python - 在模拟中实现常见的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com