raptor96 - 1 month ago 9x

Python Question

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.

In other words, I want to create a curve (gaussian) with mu and sigma and

`n`

How to do this?

Answer

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
```

Source (Stackoverflow)

Comments