## Friday 29 March 2024

### NumPy's random number arrays

NumPy's random number generation capabilities are essential for various tasks, from simulations to statistical analysis.

1. np.random.rand()

• Purpose: Generates an array of random floating-point values uniformly distributed between 0 (inclusive) and 1 (exclusive).

• Syntax:
Python
np.random.rand(d0, d1, ..., dn)

• d0, d1, ..., dn: Integers specifying the shape (dimensions) of the desired array.

• Example:
Python
import numpy as np

random_array = np.random.rand(3# 1D array with 3 random values
print(random_array)  # Output (values will vary on each run):
# [0.234523  0.789012  0.567823]

random_matrix = np.random.rand(2, 2# 2x2 matrix of random values
print(random_matrix)  # Output (values will vary):
# [[0.12345  0.87654]
#  [0.98765  0.34567]]

2. np.random.randn()

• Purpose: Generates an array of random values from a standard normal distribution (mean 0, standard deviation 1).

• Syntax:
Python
np.random.randn(d0, d1, ..., dn)

• Same as np.random.rand() for specifying the shape.

• Example:
Python
standard_normal_array = np.random.randn(4)
print(standard_normal_array)  # Output (values will vary):
# [-0.3456  1.2345  0.7890 -0.5678]

3. np.random.randint()

• Purpose: Generates an array of random integers from a specified range (inclusive at the lower bound, exclusive at the upper bound).

• Syntax:
Python
np.random.randint(low, high, size=d, dtype='l')

• low: Lower bound (inclusive).

• high: Upper bound (exclusive).

• size: Number of elements in the array (optional).

• dtype (optional): Data type of the elements (default is 'l' for long integer).

• Example:
Python
dice_rolls = np.random.randint(1, 7, size=10# Simulates 10 dice rolls
print(dice_rolls)  # Output (values will vary):
# [4 3 2 5 6 1 3 5 4 2]

random_ints_0_to_9 = np.random.randint(0, 10, size=(2, 3))  # 2x3 matrix of random integers between 0 and 9
print(random_ints_0_to_9)  # Output (values will vary):
# [[3 7 8]
#  [1 5 0]]

Key Points:

• Seeding (Optional): Use np.random.seed() to set the initial state of the random number generator for reproducibility in your simulations.

• Versatility: NumPy's random number generation caters to various scenarios through these functions and other distributions available in the random module.

Let me know if you'd like to explore:

• Other random number distributions (e.g., binomial, Poisson)

• Seeding for reproducibility

• Applications of random numbers in simulations or calculations