问题描述
我能够像这样在numpy中生成正态分布的随机样本.
I am able to generate random samples of normal distribution in numpy like this.
>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)
但是,它们显然是随机的.如何按顺序生成数字,也就是说,值应该像正态分布一样上升和下降.
But they are in random order, obviously. How can I generate numbers in order, that is, values should rise and fall like in a normal distribution.
换句话说,我想创建一个具有mu和sigma且我可以输入的点数为n
的曲线(高斯曲线).
In other words, I want to create a curve (gaussian) with mu and sigma and n
number of points which I can input.
该怎么做?
推荐答案
到(1)生成大小为n的x坐标的随机样本(根据正态分布)(2)评估x值处的正态分布(3)按位置处的正态分布的大小对x值进行排序,这将达到目的:
To (1) generate a random sample of x-coordinates of size n (from the normal distribution) (2) evaluate the normal distribution at the x-values (3) sort the x-values by the magnitude of the normal distribution at their positions, this will do the trick:
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
这篇关于按顺序生成正态分布python,numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!