Understanding the Difference Between np.random.rand() and np.random.randn() in NumPy
When working with NumPy in Python, generating random numbers is a common task. Two functions that often cause confusion are
np.random.rand()
np.random.randn()
They look almost the same, but they generate numbers from different distributions. Let’s explore the difference with examples and outputs.
1. np.random.rand() → Uniform Distribution
Generates numbers between 0 and 1.
Follows a uniform distribution → every number in the range
[0, 1)has the same probability.Values are always non-negative.
Example:
import numpy as np
# 5 random numbers between 0 and 1
print(np.random.rand(5))
Sample Output:
[0.3745 0.9507 0.7319 0.5986 0.1560]
Visualization
import matplotlib.pyplot as plt
plt.subplot(1, 2, 1)
plt.hist(data_uniform, bins=30, color="skyblue", edgecolor="black")
plt.title("Uniform Distribution (np.random.rand)")
plt.xlabel("Value")
plt.ylabel("Frequency")
Output Plot:
(Flat distribution, values evenly spread in [0,1))

2. np.random.randn() → Standard Normal Distribution
Generates numbers from a standard normal distribution (Gaussian).
Mean = 0, Standard Deviation = 1.
Values can be negative or positive, but most cluster around 0.
Example
# 5 random numbers from standard normal distribution
print(np.random.randn(5))
Sample Output:
[-0.479 0.930 -0.185 -1.063 0.323]
Visualization
plt.subplot(1, 2, 2)
plt.hist(data_normal, bins=30, color="lightcoral", edgecolor="black")
plt.title("Normal Distribution (np.random.randn)")
plt.xlabel("Value")
plt.ylabel("Frequency")
Output Plot:
(Bell-shaped curve centered around 0)

3. Side-by-Side Comparison
plt.figure(figsize=(12, 5))
# Uniform
plt.subplot(1, 2, 1)
plt.hist(data_uniform, bins=30, color="skyblue", edgecolor="black")
plt.title("Uniform Distribution (np.random.rand)")
plt.xlabel("Value")
plt.ylabel("Frequency")
# Normal
plt.subplot(1, 2, 2)
plt.hist(data_normal, bins=30, color="lightcoral", edgecolor="black")
plt.title("Normal Distribution (np.random.randn)")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.tight_layout()
plt.show()
Output Plot (Comparison):
Left (
rand) → flat distribution in [0,1).Right (
randn) → bell curve centered at 0.
4. Quick Summary
| Function | Distribution | Range | Mean | Std. Dev |
rand() | Uniform | [0, 1) | ~0.5 | ~0.29 |
randn() | Normal (Gaussian) | (-∞, ∞) | 0 | 1 |
Key Takeaway
np.random.rand()→ Flat uniform randomness between 0 and 1.np.random.randn()→ Gaussian randomness centered at 0.
The difference is crucial in statistics, simulations and machine learning, where the choice of distribution directly impacts results.
