Create normally distributed arrays
Generate synthetic Gaussian-valued features or noise with a specified tensor shape.
NumPy · Function
Draw samples from the standard normal distribution. With dimensions, np.random.randn returns an array of that shape; without dimensions, it returns one float.
Call np.random.randn with zero or more dimension arguments. With no dimensions it returns one Python float; with positive integer-like dimensions it returns an ndarray whose shape follows those arguments, containing samples from a normal distribution with mean 0 and variance 1.
numpy.random.randn(d0, d1, ..., dn)| Name | Type | Description |
|---|---|---|
d0, d1, ..., dn | int, optional | Dimensions of the returned array; dimensions should be positive integer-like values. If omitted, one scalar is returned. |
ndarray or float: an array shaped (d0, d1, ..., dn) containing floating-point standard-normal samples, or one float when no parameters are supplied.
import numpy as np
rng = np.random.default_rng(42)
z = rng.standard_normal((2, 3))
print(z.shape) # (2, 3)
sample = np.random.randn()
print(isinstance(sample, float))Creates a reproducible standard-normal array with the recommended generator method, then demonstrates that randn() without dimensions returns one scalar.
Generate synthetic Gaussian-valued features or noise with a specified tensor shape.
Produce one standard-normal deviate for a stochastic calculation.
Construct N(mu, sigma²) values by scaling and shifting standard-normal output.
It samples from the standard normal distribution, so the mean is 0 and the variance is 1. With dimensions, it returns floating-point samples arranged in the requested shape.
Follow-up: How would you sample from N(mu, sigma²)? Multiply the output by sigma and add mu: mu + sigma * np.random.randn(...).
No arguments return one Python float. Passing d0, d1, and so on returns an ndarray with shape (d0, d1, ..., dn).
Follow-up: What is the modern alternative? Use a Generator instance and call its standard_normal method, passing a tuple or integer shape.
Each dimension is supplied as a separate positional argument, such as np.random.randn(2, 4), producing a 2-by-4 array. The dimensions should be positive integer-like values.
Follow-up: How can the same shape be expressed with the modern API? Call rng.standard_normal((2, 4)) on a Generator instance.
numpy.random.standard_normalnumpy.random.Generator.standard_normal