0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.random.randn in NumPy for Random Normal Data

Use np.random.randn to generate samples from a standard normal distribution (mean 0, variance 1). You can specify the shape by passing dimensions as arguments, like np.random.randn(3, 2) for a 3x2 array of random values.
๐Ÿ“

Syntax

The basic syntax of np.random.randn is to pass one or more integer arguments that define the shape of the output array. It returns samples from a standard normal distribution (mean 0, standard deviation 1).

  • np.random.randn(d0, d1, ..., dn): Generates an array of shape (d0, d1, ..., dn).
  • If no arguments are given, it returns a single float.
python
import numpy as np

# Generate a single random number from standard normal distribution
single_value = np.random.randn()

# Generate a 1D array of 5 random numbers
array_1d = np.random.randn(5)

# Generate a 2D array of shape 3x2
array_2d = np.random.randn(3, 2)
๐Ÿ’ป

Example

This example shows how to generate a 3x3 array of random numbers from the standard normal distribution and print it.

python
import numpy as np

# Generate a 3x3 array of random numbers
random_array = np.random.randn(3, 3)
print(random_array)
Output
[[ 0.49671415 -0.1382643 0.64768854] [-0.23415337 -0.23413696 1.57921282] [ 0.76743473 -0.46947439 0.54256004]]
โš ๏ธ

Common Pitfalls

Common mistakes when using np.random.randn include:

  • Confusing randn with rand: randn generates normal distribution values, while rand generates uniform distribution values between 0 and 1.
  • Passing a tuple instead of separate arguments: np.random.randn((3,2)) will cause an error; use np.random.randn(3, 2) instead.
  • Expecting values outside the normal distribution range: values can be any real number, not limited to 0-1.
python
import numpy as np

# Wrong: passing a tuple causes an error
try:
    np.random.randn((3, 2))
except TypeError as e:
    print(f"Error: {e}")

# Correct usage
correct_array = np.random.randn(3, 2)
print(correct_array)
Output
Error: 'tuple' object cannot be interpreted as an integer [[ 0.49671415 -0.1382643 ] [-0.23415337 -0.23413696] [ 1.57921282 0.76743473]]
๐Ÿ“Š

Quick Reference

Summary tips for using np.random.randn:

  • Generates samples from a standard normal distribution (mean 0, std 1).
  • Arguments specify the shape of the output array.
  • Pass dimensions as separate integers, not as a tuple.
  • Returns a float if no arguments are given.
โœ…

Key Takeaways

Use np.random.randn with integer arguments to get arrays of standard normal random values.
Do not pass a tuple as a single argument; pass dimensions separately.
np.random.randn returns floats from a normal distribution with mean 0 and std 1.
If no arguments are given, it returns a single float value.
Remember np.random.randn differs from np.random.rand which generates uniform values.