非随机抽样版本np.随机标准

2024-09-30 00:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图生成一个遵循精确高斯分布的数组。np.随机.正态高斯随机抽样的意思是,我可以用高斯随机抽样。所以数组将产生一个柱状图,它遵循一个精确的高斯分布,而不仅仅是下面所示的近似高斯分布。在

mu, sigma = 10, 1
s = np.random.normal(mu, sigma, 1000)

fig = figure()
ax = plt.axes()

totaln, bbins, patches = ax.hist(s, 10, normed = 1, histtype = 'stepfilled', linewidth = 1.2)

plt.show()

Tags: npfigpltrandom数组axsigmafigure
1条回答
网友
1楼 · 发布于 2024-09-30 00:39:19

如果你想要一个精确的高斯直方图,不要生成点。你可以从观测点得到一个“精确的”高斯分布,仅仅是因为你不能在一个直方图单元内有一个点的分数。在

相反,以条形图的形式绘制曲线。在

import numpy as np
import matplotlib.pyplot as plt

def gaussian(x, mean, std):
    scale = 1.0 / (std * np.sqrt(2 * np.pi))
    return scale * np.exp(-(x - mean)**2 / (2 * std**2))

mean, std = 2.0, 5.0
nbins = 30
npoints = 1000

x = np.linspace(mean - 3 * std, mean + 3 * std, nbins + 1)
centers = np.vstack([x[:-1], x[1:]]).mean(axis=0)
y = npoints * gaussian(centers, mean, std)

fig, ax = plt.subplots()
ax.bar(x[:-1], y, width=np.diff(x), color='lightblue')

# Optional...
ax.margins(0.05)
ax.set_ylim(bottom=0)

plt.show()

enter image description here

相关问题 更多 >

    热门问题