我需要知道如何在500到600之间生成1000个随机数,这些随机数在python中具有平均值= 550和标准偏差= 30。
import pylab
import random
xrandn = pylab.zeros(1000,float)
for j in range(500,601):
xrandn[j] = pylab.randn()
???????
答案 0 :(得分:8)
您正在寻找stats.truncnorm:
import scipy.stats as stats
a, b = 500, 600
mu, sigma = 550, 30
dist = stats.truncnorm((a - mu) / sigma, (b - mu) / sigma, loc=mu, scale=sigma)
values = dist.rvs(1000)
答案 1 :(得分:4)
您的问题还有其他选择。维基百科有continuous distributions with bounded intervals列表,具体取决于您可以使用正确的参数获得所需特征的分布。例如,如果您想要“有界高斯钟”(未截断)之类的东西,您可以选择(缩放)beta distribution:
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
def my_distribution(min_val, max_val, mean, std):
scale = max_val - min_val
location = min_val
# Mean and standard deviation of the unscaled beta distribution
unscaled_mean = (mean - min_val) / scale
unscaled_var = (std / scale) ** 2
# Computation of alpha and beta can be derived from mean and variance formulas
t = unscaled_mean / (1 - unscaled_mean)
beta = ((t / unscaled_var) - (t * t) - (2 * t) - 1) / ((t * t * t) + (3 * t * t) + (3 * t) + 1)
alpha = beta * t
# Not all parameters may produce a valid distribution
if alpha <= 0 or beta <= 0:
raise ValueError('Cannot create distribution for the given parameters.')
# Make scaled beta distribution with computed parameters
return scipy.stats.beta(alpha, beta, scale=scale, loc=location)
np.random.seed(100)
min_val = 1.5
max_val = 35
mean = 9.87
std = 3.1
my_dist = my_distribution(min_val, max_val, mean, std)
# Plot distribution PDF
x = np.linspace(min_val, max_val, 100)
plt.plot(x, my_dist.pdf(x))
# Stats
print('mean:', my_dist.mean(), 'std:', my_dist.std())
# Get a large sample to check bounds
sample = my_dist.rvs(size=100000)
print('min:', sample.min(), 'max:', sample.max())
输出:
mean: 9.87 std: 3.100000000000001
min: 1.9290674232087306 max: 25.03903889816994
概率密度函数图:
请注意,在这种情况下,并非每种可能的边界组合,均值和标准差都会产生有效分布,并且取决于alpha
和beta
的结果值,概率密度函数可能看起来像一个“倒钟”(即使平均值和标准偏差仍然是正确的)。