Introduction to Random Numbers in NumPy
Random Numbers in NumPy
A random number is a value that is generated unpredictably and without any discernible pattern or order.
Generate Random Number
In NumPy, you can generate random numbers using the numpy.random
module, which provides various functions for generating random values from different probability distributions.
Here are a few commonly used functions for generating random numbers:
Using np.random.rand()
The np.random.rand()
function generates random numbers from a uniform distribution between 0 and 1. It takes the shape of the desired output as arguments.
import numpy as np
# Generate a random number between 0 and 1
random_num = np.random.rand()
print(random_num) # Output: 0.784599687134
Using np.random.randint()
The np.random.randint()
function generates random integers within a specified range. You can specify the lower and upper bounds of the range and the shape of the output.
import numpy as np
# Generate a random integer between 1 and 10
random_int = np.random.randint(1, 10)
print(random_int) # Output: 5
Using np.random.randn()
The np.random.randn()
function generates random numbers from a standard normal distribution (mean 0, standard deviation 1). You can specify the shape of the output.
import numpy as np
# Generate a random number from a standard normal distribution
random_num = np.random.randn()
print(random_num) # Output: 0.43104507319
Using np.random.choice()
The np.random.choice()
function generates random samples from a given 1-D array or list. You can specify the array of values and the number of samples to draw.
import numpy as np
# Generate a random sample from a given array
arr = np.array([1, 2, 3, 4, 5])
random_sample = np.random.choice(arr, size=3, replace=False)
print(random_sample) # Output: [2 3 1]