February 8, 2025

Random Uniform Distribution in Python

In Python, generating random numbers with a uniform distribution can be accomplished using various libraries. The most commonly used library for this purpose is random from Python’s standard library. For more advanced needs, you might use libraries like NumPy.

1. Using the random Module

The random module provides the uniform() function to generate random floating-point numbers within a specified range. The syntax is as follows:

import random

# Generate a random float between a and b
a = 1
b = 10
random_number = random.uniform(a, b)
print(random_number)
    

In this example, random.uniform(a, b) generates a random float between a and b (inclusive of a and exclusive of b).

2. Using NumPy

For more control and efficient random number generation, especially in scientific computing, you can use the numpy library. The numpy.random module provides the uniform() function for generating random numbers with a uniform distribution.

import numpy as np

# Generate a random float between low and high
low = 1
high = 10
random_number = np.random.uniform(low, high)
print(random_number)
    

Here, np.random.uniform(low, high) generates a random float between low (inclusive) and high (exclusive).

3. Generating Multiple Random Numbers

Both random and numpy allow generating multiple random numbers at once. This is useful for creating arrays of random values.

3.1. Using random

import random

# Generate a list of 5 random floats between a and b
a = 1
b = 10
random_numbers = [random.uniform(a, b) for _ in range(5)]
print(random_numbers)
    

3.2. Using numpy

import numpy as np

# Generate an array of 5 random floats between low and high
low = 1
high = 10
random_numbers = np.random.uniform(low, high, 5)
print(random_numbers)
    

4. Conclusion

Generating random numbers with a uniform distribution is straightforward in Python using the random module for basic needs or numpy for more advanced applications. Both libraries provide convenient functions for generating random numbers within a specified range, either as single values or arrays.