Generating random numbers is an essential operation for simulations, initializing machine learning models, and creating test data. While Python’s standard random module can generate random numbers, using NumPy allows you to generate large amounts of random numbers as arrays all at once and at high speed.
This article explains the basic method of generating random numbers between 0.0 and 1.0 (exclusive) using NumPy’s np.random.rand function.
Overview of the np.random.rand Function
np.random.rand() is a function that generates “uniform random numbers” that are greater than or equal to 0.0 and less than 1.0. By specifying the number of elements you want as an argument, it returns a NumPy array (ndarray) containing that many random numbers.
The major difference from the standard library is that you can create an array of a specified size at once without writing a loop.
Implementation Sample Code
Below is sample code that generates 5 random numbers and checks the state of the entire array and individual values. This assumes a scenario where you are generating 5 random parameters for a simulation experiment.
import numpy as np
def generate_simulation_parameters():
"""
Function to generate and display a random number array using NumPy.
"""
# Generate 5 random numbers between 0.0 (inclusive) and 1.0 (exclusive)
# Specify the number of elements to generate as an argument
simulation_values = np.random.rand(5)
print("--- Generated Random Array (ndarray) ---")
print(simulation_values)
print("\n--- Output formatted individual values ---")
# Access and display each element in the array
for val in simulation_values:
# Display up to 4 decimal places
print(f"Parameter Value: {val:.4f}")
if __name__ == "__main__":
generate_simulation_parameters()
Example Execution Result
Since random numbers are used, different values will be output each time you run the code.
--- Generated Random Array (ndarray) ---
[0.417022 0.72032449 0.00011437 0.30233257 0.14675589]
--- Output formatted individual values ---
Parameter Value: 0.4170
Parameter Value: 0.7203
Parameter Value: 0.0001
Parameter Value: 0.3023
Parameter Value: 0.1468
Key Points of the Code
- Bulk Generation: Simply writing
np.random.rand(5)generates an array with 5 elements. If you want to generate a multi-dimensional array (matrix), you can add arguments likenp.random.rand(2, 3)to create a 2×3 random matrix. - Type: The type of the generated data is
float64(floating-point number). - Range: The range of the generated value x is
0 <= x < 1. Please note that 1.0 is not included.
By utilizing this function, you can reduce the amount of code written when handling large amounts of data, improving both code readability and processing speed.
