Python : 按钟声顺序生成正态分布

Python : Generate normal distribution in the order of the bell

我想按铃的顺序生成正态分布。 我使用此代码生成数字:

import numpy as np

mu,sigma,n = 0.,1.,1000

def normal(x,mu,sigma):
    return ( 2.*np.pi*sigma**2. )**-.5 * np.exp( -.5 * (x-mu)**2. / sigma**2. )

x = np.random.normal(mu,sigma,n) #generate random list of points from normal distribution
y = normal(x,mu,sigma) #evaluate the probability density at each point
x,y = x[np.argsort(y)],np.sort(y) #sort according to the probability density

这是建议的代码:

但数字不遵循钟形。 有任何想法吗? 非常感谢

有几件事让您感到困惑。

random.normal 从钟形曲线中随机抽取 n 个数字

所以你有 1000 个数字,每个数字都不同,都是从曲线中绘制的。要重新创建曲线,您需要应用一些分箱。每个 bin 中的点数将重新创建曲线(仅一个点本身很难代表概率)。在只有 1000 点的 x 向量上使用一些广泛的分箱:

h,hx=np.histogram(x,bins=50)

并将 h 绘制为 hx 的函数(所以我将您的千数分为 50 个箱子,y 轴将显示箱子中的点数:

现在我们可以看到 x 是从钟形分布中得出的 - 落入中心区间的机会由高斯分布决定。这是一个采样,因此每个点当然可能会有所不同 - 您使用的点越多,合并越精细,效果就越好(更平滑)。

y = normal(x,mu,sigma)

这只是在任何给定的 x 下评估高斯分布,所以实际上,提供 normal 任何围绕您的均值 (mu) 的数字列表,它将精确计算钟形曲线(确切的可能性)。绘制 yx 的对比图(您的 x 本身是高斯分布并不重要,但它是均值附近的 1000 点,因此它可以重新创建函数):

看看有多流畅?那是因为它不是采样,而是函数的精确计算。您可以使用 0 附近的任何 1000 个点,它看起来也一样好。

您的代码运行良好。

import numpy as np
import matplotlib.pyplot as plt

mu,sigma,n = 0.,1.,1000

def normal(x,mu,sigma):
    return ( 2.*np.pi*sigma**2. )**-.5 * np.exp( -.5 * (x-mu)**2. / sigma**2. )

x = np.random.normal(mu,sigma,n) 
y = normal(x,mu,sigma) 


plt.plot(x,y)