2016-01-20 147 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