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
scaleas zero or negative, which is invalid because standard deviation must be positive. - Confusing
loc(mean) withscale(standard deviation). - Not setting
sizeproperly, 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
| Parameter | Description | Example |
|---|---|---|
| loc | Mean of the distribution | 0 |
| scale | Standard deviation (must be > 0) | 1 |
| size | Number of samples or shape | 5 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.