如何模拟固定区间的变量?

2024-05-13 23:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图模拟一个真实生活过程的表现。历史上测量过的变量显示了一个固定的区间,所以越低或越大,这些值在物理上是不可能的。你知道吗

为了模拟过程输出,每个输入变量的历史数据分别表示为最佳拟合概率分布(使用这种方法:Fitting empirical distribution to theoretical ones with Scipy (Python)?)。你知道吗

然而,当模拟n次时得到的理论分布并不代表实际生活中预期的最小值和最大值。我正在考虑对每个模拟应用一个try-except-test来检查每个模拟值是否在预期间隔之间,但我不确定这是否是处理这个问题的最佳方法,因为没有达到实验平均值和方差。你知道吗


Tags: to方法过程withones物理scipy历史
1条回答
网友
1楼 · 发布于 2024-05-13 23:30:36

可以在numpy中使用布尔掩码来重新生成超出所需边界的值。例如:

def random_with_bounds(func, size, bounds):
    x = func(size=size)
    r = (x < bounds[0]) | (x > bounds[1])
    while r.any():
        x[r] = func(size=r.sum())
        r[r] = (x[r] < bounds[0]) | (x[r] > bounds[1])
    return x

然后你可以像这样使用它:

random_with_bounds(np.random.normal, 1000, (-1, 1))

另一个版本通过np.argwhere使用索引数组,性能略有提高:

def random_with_bounds_2(func, size, bounds):
    x = func(size=size)
    r = np.argwhere((x < bounds[0]) | (x > bounds[1])).ravel()
    while r.size > 0:
        x[r] = func(size=r.size)
        r = r[(x[r] < bounds[0]) | (x[r] > bounds[1])]
    return x

相关问题 更多 >