Generate Random Numbers From The Uniform Distribution using NumPy

The uniform distribution generates random numbers where each value within a specified range has an equal probability of being selected. NumPy's random.uniform() function provides an efficient way to generate such random numbers for statistical analysis, simulations, and machine learning applications.

Syntax

numpy.random.uniform(low=0.0, high=1.0, size=None)

Parameters

low: Lower boundary of the output interval. All values generated will be greater than or equal to low. Default is 0.0.

high: Upper boundary of the output interval. All values generated will be less than high. Default is 1.0.

size: Output shape. If given as an integer, returns a 1-D array of that length. If given as a tuple, returns an array with that shape.

Using Default Range (0 to 1)

Generate random numbers from the default uniform distribution between 0 and 1 ?

import numpy as np

# Generate five random numbers from uniform distribution (0 to 1)
random_numbers = np.random.uniform(size=5)

print("Random numbers (0 to 1):", random_numbers)
Random numbers (0 to 1): [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]

Using Custom Range

Specify custom lower and upper bounds for the uniform distribution ?

import numpy as np

# Generate random numbers between 10 and 20
random_numbers = np.random.uniform(low=10, high=20, size=8)

print("Random numbers (10 to 20):", random_numbers)
Random numbers (10 to 20): [15.8092282  18.6463381  17.3235249  11.0820393  11.4374817  19.0251378
 14.2054299  18.1820786]

Generating 2D Arrays

Create multi-dimensional arrays of random numbers from uniform distribution ?

import numpy as np

# Generate a 3x4 array of random numbers between 0 and 100
random_array = np.random.uniform(low=0, high=100, size=(3, 4))

print("2D array of random numbers:")
print(random_array)
2D array of random numbers:
[[54.881350   71.518937   60.276338   54.488318  ]
 [42.365480   64.589411   43.758721   89.177300  ]
 [96.366276   38.344152   79.172504   52.889492  ]]

Common Use Cases

Use Case Range Example
Probability values 0 to 1 np.random.uniform(size=100)
Test scores 0 to 100 np.random.uniform(0, 100, size=50)
Temperature data -10 to 40 np.random.uniform(-10, 40, size=(7, 24))

Conclusion

NumPy's uniform() function efficiently generates random numbers with equal probability across any specified range. Use it for creating synthetic datasets, Monte Carlo simulations, and statistical sampling applications.

Updated on: 2026-03-27T12:03:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements