We use uniform random numbers to get values that are equally likely anywhere in a range. This helps when we want to simulate random events or test ideas with random data.
0
0
Uniform random with random() in NumPy
Introduction
When simulating rolling a fair dice many times.
When picking random points inside a square or rectangle.
When testing how a program behaves with random inputs.
When creating random samples for experiments.
When generating random colors or positions in a game.
Syntax
NumPy
numpy.random.random(size=None)size is optional and decides how many random numbers you get.
The numbers are between 0 (inclusive) and 1 (exclusive).
Examples
Get one random number between 0 and 1.
NumPy
import numpy as np x = np.random.random() print(x)
Get an array of 5 random numbers between 0 and 1.
NumPy
import numpy as np arr = np.random.random(5) print(arr)
Get a 2 by 3 matrix of random numbers between 0 and 1.
NumPy
import numpy as np matrix = np.random.random((2,3)) print(matrix)
Sample Program
This program shows how to get one random number, an array of random numbers, and a matrix of random numbers using numpy.random.random().
NumPy
import numpy as np # Generate one random number one_num = np.random.random() print(f"One random number: {one_num}") # Generate 4 random numbers in an array arr = np.random.random(4) print("Array of 4 random numbers:", arr) # Generate a 3x2 matrix of random numbers matrix = np.random.random((3, 2)) print("3x2 matrix of random numbers:") print(matrix)
OutputSuccess
Important Notes
Each time you run the code, the random numbers will change.
You can set a seed with np.random.seed(number) to get the same random numbers every time, which helps with testing.
Summary
Uniform random numbers are equally likely anywhere between 0 and 1.
Use numpy.random.random() to get these numbers.
You can get one number, an array, or a matrix by changing the size parameter.