NumPy Tutorial NumPy Statistics NumPy References

NumPy - random.randn() function



The NumPy random.randn() function returns random values drawn from standard normal distribution. The function creates an array of the given shape and populate it with random samples drawn from standard normal distribution, N(0,1).

For generating random values from N(μ,σ2), the following relationship can be used:

σ * np.random.randn() + μ

Syntax

numpy.random.randn(d0, d1, ..., dn)

Parameters

d0, d1, ..., dn Optional. Specify dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Return Value

Returns normally distributed random values in a given shape.

Example:

In the example below, random.randn() function is used to generate a single normally distributed random value.

import numpy as np

x = np.random.randn()

#printing x
print("x =", x)

The output of the above code will be:

x = -0.10260518706470677

Example:

In the example below, the function is used to generate normally distributed random values in the specified shape.

import numpy as np

#creating an array of given size filled with
#normally distributed random numbers
x = np.random.randn(5, 3)

#printing x
print(x)

The output of the above code will be:

[[-2.00531288  1.17042872 -0.27274007]
 [-1.23449724 -1.45153424  0.80607412]
 [-1.26947172 -0.87846179 -0.91597572]
 [ 0.2556099  -2.254434    1.79726119]
 [ 0.15107511  0.59157496  0.17703119]]

Example:

By using σ * np.random.randn() + μ relationship, we can choose any normal distribution to the draw the sample from.

import numpy as np

#creating an array of given size filled with
#normally distributed random numbers
#mean = 5, standard deviation = 10
x = 10 * np.random.randn(5, 3) + 5

#printing x
print(x)

The output of the above code will be:

[[ -3.06146172   1.23819782   5.33350296]
 [ 17.01493033  25.46120405  20.75852474]
 [  0.96942822  -7.66655047  24.40159379]
 [ 24.14518988 -16.5792282    0.69661644]
 [ -6.99760155 -16.72949518  -4.13600001]]

❮ NumPy - Random