Random Number Generation in NumPy
NumPy provides functions to generate random numbers efficiently. The main functions used for random number generation are:
- random.rand() - Generates random numbers from a uniform distribution between 0 and 1.
- random.randn() - Generates random numbers from a normal (Gaussian) distribution.
- random.randint() - Generates random integers within a specified range.
1. Generating Random Numbers with random.rand()
The random.rand() function generates an array of random numbers between 0 and 1.
import numpy as np rand_numbers = np.random.rand(3, 3) print(rand_numbers)
Example Output:
[[0.548 0.715 0.602] [0.544 0.423 0.645] [0.437 0.891 0.963]]
2. Generating Random Numbers with random.randn()
The random.randn() function generates numbers from a standard normal distribution (mean = 0, variance = 1).
randn_numbers = np.random.randn(3, 3) print(randn_numbers)
Example Output:
[[-1.432 0.687 0.212] [ 1.120 -0.319 -0.461] [ 0.875 -0.624 0.533]]
3. Generating Random Integers with random.randint()
The random.randint() function generates random integers within a specified range.
randint_numbers = np.random.randint(1, 10, (3, 3)) print(randint_numbers)
Example Output:
[[5 2 8] [7 9 1] [4 3 6]]
Conclusion
NumPy's random number generation functions allow for creating random datasets for simulations, testing, and data analysis. The rand() function generates uniform numbers, randn() generates normally distributed numbers, and randint() generates random integers within a given range.