0
0
NumpyHow-ToBeginner ยท 3 min read

How to Generate Normal Distribution with NumPy

Use numpy.random.normal(loc, scale, size) to generate random numbers from a normal distribution. Here, loc is the mean, scale is the standard deviation, and size is the number of samples.
๐Ÿ“

Syntax

The function numpy.random.normal(loc, scale, size) generates random numbers from a normal (Gaussian) distribution.

  • loc: The mean (center) of the distribution.
  • scale: The standard deviation (spread) of the distribution.
  • size: The number of random samples to generate. It can be an integer or a tuple for multi-dimensional arrays.
python
numpy.random.normal(loc=0.0, scale=1.0, size=None)
๐Ÿ’ป

Example

This example generates 5 random numbers from a normal distribution with mean 0 and standard deviation 1.

python
import numpy as np

samples = np.random.normal(loc=0, scale=1, size=5)
print(samples)
Output
[ 0.49671415 -0.1382643 0.64768854 1.52302986 -0.23415337]
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using scale as zero or negative, which is invalid because standard deviation must be positive.
  • Confusing loc (mean) with scale (standard deviation).
  • Not setting size properly, which can lead to unexpected output shapes.
python
import numpy as np

# Wrong: scale is zero (invalid)
try:
    np.random.normal(loc=0, scale=0, size=3)
except Exception as e:
    print(f"Error: {e}")

# Right: scale is positive
samples = np.random.normal(loc=0, scale=1, size=3)
print(samples)
Output
Error: scale <= 0 [ 0.15494743 0.37816252 -0.88778575]
๐Ÿ“Š

Quick Reference

ParameterDescriptionExample
locMean of the distribution0
scaleStandard deviation (must be > 0)1
sizeNumber of samples or shape5 or (2,3)
โœ…

Key Takeaways

Use numpy.random.normal(loc, scale, size) to generate normal distribution samples.
Set loc as the mean and scale as the positive standard deviation.
Specify size to control how many samples or the shape of the output.
Avoid zero or negative scale values to prevent errors.
Output is a NumPy array of random values following the normal distribution.