使用 beta 分布生成特定范围内的随机数

Generate random numbers in a specific range using beta distribution

我想使用 a=2.2 和 b=1 的 beta 分布在 (0.0001,0.03) 范围内生成 100 万和 1000 万个数据点。提前致谢!

我试过这个:

from scipy.stats import beta
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)
a, b = 2.2, 1
#Generated pdf of required range
x = np.linspace(0.0001, 0.03, 100)

ax.plot(x, beta.pdf(x, a, b),
       'k-', lw=5, alpha=0.6, label='beta pdf')

r = beta.rvs(a, b, size=1000) #Generating values
print(r)

'r'中的值不在 (0.0001,0.03) 范围内。

对于您使用的 alpha 和 beta 参数,beta 分布是从 (0, 0)(1, 2.2) 的相当直线。您感兴趣的范围 (0.0001, 0.03) 既是 0 到 1 范围内的一小部分,但对于您选择的参数来说也有很​​小的概率。

要真正生成100万或1000万个点,你需要不断地生成点并将它们累加到一个数组中。

from scipy.stats import beta
import numpy as np

b_dist = beta(a=2.2, b=1)
target_length = 1_000_000
points = np.array([])

while points.size < target_length:
    # generate new points
    x = b_dist.rvs(1_000_000)
    # find the indices that match criteria
    ix = x < 0.03
    ix = ix & (0.0001 < x)
    points = np.hstack([points, x[ix]])