How to generate normal distribution samples (with specific mean and variance) in Python?

Question:

I’m new to Python and I would like to generate 1000 samples having normal distribution with specific mean and variance. I got to know a library called NumPy and I am wondering if I used it in the correct way. Here’s my code:

import numpy
a = numpy.random.normal(0, 1, 1000)
print(a)

where 0 is the mean, 1 is the standard deviation (which is square root of variance), and 1000 is the size of the population.

Is this the correct way, or is there a better way to do it?

Asked By: Green Squirtle

||

Answers:

Yes, that’s the way to generate 1000 samples in a normal distribution N(0,1).

And you can see that the output of these 1000 samples are mostly within -3 and 3, as 99.73% will be within plus/minus 3 standard deviations:

enter image description here

The colorful graph is done using below codes:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
np.random.seed(7)
y = np.random.normal(0, 1, 1000)
colors = cm.rainbow(np.linspace(0, 1, 11))
for x,y in enumerate(y):
    plt.scatter(x,y, color=colors[np.random.randint(0,10)])

However it’s faster to generate a single-color chart:

np.random.seed(7)
x = [i for i in range(1, 1001)]
y = np.random.normal(0, 1, 1000)
plt.scatter(x, y, color='navy')
Answered By: perpetualstudent
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.