生成 上的截断正态分布的随机数
定义好
clip_a # a
clip_b # b
mean # \mu
std # \sigma
接着
a, b = (clip_a - mean) / std, (clip_b - mean) / std
scipy.stats.truncnorm(a, b, loc=mean, scale=std)
例子:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import truncnorm
# 生成 [-1, 1] 上 N(1, 4) 的截断正态分布
clip_a, clip_b = -1, 1
mean = 1
std = 2
a, b = (clip_a - mean) / std, (clip_b - mean) / std
dist = truncnorm(a, b, loc=mean, scale=std)
x_range = np.linspace(-1, 1, 100)
plt.plot(x_range, dist.pdf(x_range))
sns.histplot(dist.rvs(size=100000), stat="density")