Like rand(), randn() takes each dimension as a separate positional argument rather than a shape tuple, but unlike rand(), it draws from a Gaussian, bell curve, distribution centered at 0 with a standard deviation of 1, rather than a uniform distribution — most values cluster near 0, and values further away become progressively less likely, following the classic bell-curve shape. To get samples from a normal distribution with a different mean and standard deviation, scale and shift the result manually, or use np.random.normal() directly, which accepts those parameters explicitly.
1Understanding np.random.randn()
Like rand(), randn() takes each dimension as a separate positional argument rather than a shape tuple, but unlike rand(), it draws from a Gaussian, bell curve, distribution centered at 0 with a standard deviation of 1, rather than a uniform distribution — most values cluster near 0, and values further away become progressively less likely, following the classic bell-curve shape. To get samples from a normal distribution with a different mean and standard deviation, scale and shift the result manually, or use np.random.normal() directly, which accepts those parameters explicitly.
To sample from a normal distribution with a specific mean and standard deviation, either compute mean plus standard deviation times randn()'s output manually, or use the more explicit np.random.normal(mean, std, size) directly — the latter is usually clearer about intent.
import numpy as np
np.random.seed(0)
print(np.random.randn(3))2Practical Example
Here is a real-world application of np.random.randn() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
mean, std = 100, 15
samples = mean + std * np.random.randn(3)
print(samples)3Best Practices
Follow these guidelines when working with np.random.randn():
1. Use np.random.normal(mean, std, size) instead of manually scaling randn()'s output when you need a specific mean/standard deviation, for clearer code
2. Set a seed for reproducibility in tests or demonstrations relying on randn()'s output
3. Prefer the newer Generator API (np.random.default_rng().standard_normal()) over the legacy randn() in new code
Tip: To sample from a normal distribution with a specific mean and standard deviation, either compute mean plus standard deviation times randn()'s output manually, or use the more explicit np.random.normal(mean, std, size) directly — the latter is usually clearer about intent.
import numpy as np
np.random.seed(0)
print(np.random.randn(3))