如何模拟具有固定间隔的变量?

how to simulate a variable with fixed interval?

我正在尝试模拟真实生活过程的表现。历史上测量的变量显示一个固定的区间,因此低于或高于这些值在物理上是不可能的。

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

然而,模拟 n 次时得到的理论分布并不代表现实生活中预期的最小值和最大值。我正在考虑对每个模拟应用 try-except 测试以检查每个模拟值是否在预期间隔之间,但我不确定这是否是处理此问题的最佳方法,因为未实现实验均值和方差。

您可以在 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