python的标准随机数生成器模块_Python:带均值和标准差的随机数生成器
你的問題也有其他選擇。Wikipedia有一個(gè)continuous distributions with bounded intervals的列表,這取決于分布,您可以使用正確的參數(shù)獲得所需的特性。例如,如果您想要類似“有界高斯鈴”(不截?cái)?的內(nèi)容,可以選擇(縮放的)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
概率密度函數(shù)圖:
注意,在這種情況下,并不是所有可能的界限、平均值和標(biāo)準(zhǔn)差的組合都會(huì)產(chǎn)生一個(gè)有效的分布,并且取決于alpha和beta的結(jié)果值,概率密度函數(shù)可能看起來像一個(gè)“倒鐘”(即使平均值和標(biāo)準(zhǔn)差仍然是正確的)。
總結(jié)
以上是生活随笔為你收集整理的python的标准随机数生成器模块_Python:带均值和标准差的随机数生成器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 〖全域运营实战白宝书 - 运营角色认知篇
- 下一篇: websocket python爬虫_p