NumPy Tutorial NumPy Statistics NumPy References

NumPy - matlib.randn() function



The NumPy matlib.randn() function returns a matrix filled with random floats sampled from a univariate normal (Gaussian) distribution of mean 0 and variance 1.

Syntax

numpy.matlib.randn(*args)

Parameters

*args Required. Specify shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape.

Return Value

Returns a matrix of random values drawn from the standard normal distribution with shape given by *args.

Example: Values from standard normal distribution

In the example below, matlib.randn() function is used to create a matrix of given shape containing random values from the standard normal distribution, N(0, 1).

import numpy as np
import numpy.matlib

mat = np.matlib.randn(3,3)
print(mat)

The possible output of the above code could be:

[[-0.48017485  1.19876658  1.05405775]
 [ 2.03861756  0.06356518 -0.40892882]
 [ 1.25324351  0.50041813  0.73766593]]

Example: Values from normal distribution

To create a matrix containing random values from normal distribution, N(μ, σ2), the below method can be used.

σ * np.matlib.randn() + μ

Consider the example below, where elements are taken from normal distribution, N(2, 32).

import numpy as np
import numpy.matlib

mat = 3*np.matlib.randn((3,3)) + 2
print(mat)

The possible output of the above code could be:

[[ 5.96772553  2.65834353 -1.90053868]
 [ 5.38957505  0.05528532  4.98796473]
 [-0.84263633 -2.00194974  0.39697241]]

❮ NumPy - Functions