NumPy's random module provides a suite of functions for generating random numbers and random arrays. These functions are useful for various applications, including simulations, statistical analysis, and machine learning.
import numpy as np
# Generate 5 random numbers from a uniform distribution
rand_uniform = np.random.rand(5)
# Generate 5 random numbers from a standard normal distribution
rand_normal = np.random.randn(5)
# Generate 5 random integers between 1 and 10
rand_integers = np.random.randint(1, 11, size=5)
print("Uniform random numbers:", rand_uniform)
print("Normal random numbers:", rand_normal)
print("Random integers:", rand_integers)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Randomly choose 3 elements from the array with replacement
sample_with_replacement = np.random.choice(arr, size=3, replace=True)
# Randomly choose 3 elements from the array without replacement
sample_without_replacement = np.random.choice(arr, size=3, replace=False)
print("Sample with replacement:", sample_with_replacement)
print("Sample without replacement:", sample_without_replacement)
# Shuffle the array in-place
np.random.shuffle(arr)
print("Shuffled array:", arr)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Generate a random permutation of the array
permutation = np.random.permutation(arr)
print("Random permutation:", permutation)