2016-01-20 83 views
1

我试图生成一个遵循精确高斯分布的单个数组。 np.random.normal类通过从高斯随机抽样来做到这一点,但是如何给出一些均值和西格马我如何重现和确切的高斯。所以这个数组会产生一个精确的高斯直方图,而不仅仅是一个近似的高斯,如下所示。非随机抽样版本的np.random.normal

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

回答

2

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

而是以条形图的形式绘制曲线。

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