【问题标题】:non-random sampling versions of np.random.normalnp.random.normal 的非随机抽样版本
【发布时间】:2016-04-26 16:14:02
【问题描述】:

我正在尝试生成一个遵循精确高斯分布的数组。 np.random.normal 是通过从高斯随机抽样来做到这一点的,但是在给定一些平均值和 sigma 的情况下,我如何重现和精确的高斯。因此,该数组将生成一个遵循精确高斯分布的直方图,而不仅仅是如下所示的近似高斯分布。

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()

【问题讨论】:

    标签: python python-2.7 numpy random gaussian


    【解决方案1】:

    如果您想要精确的高斯直方图,请不要生成点。您永远无法从观察点获得“精确”的高斯分布,这仅仅是因为您不能在直方图 bin 中包含一个点的一小部分。

    改为以条形图的形式绘制曲线。

    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()
    

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多