0
0
NumpyHow-ToBeginner ยท 3 min read

How to Generate Uniform Distribution with NumPy

Use numpy.random.uniform(low, high, size) to generate random numbers from a uniform distribution between low and high. The size parameter controls the shape of the output array.
๐Ÿ“

Syntax

The function numpy.random.uniform(low=0.0, high=1.0, size=None) generates random numbers uniformly distributed between low and high.

  • low: The lower boundary of the output interval (inclusive).
  • high: The upper boundary of the output interval (inclusive).
  • size: The shape of the output array. If None, returns a single float.
python
numpy.random.uniform(low=0.0, high=1.0, size=None)
๐Ÿ’ป

Example

This example shows how to generate 5 random numbers between 10 and 20 using NumPy's uniform distribution.

python
import numpy as np

# Generate 5 random numbers between 10 and 20
random_numbers = np.random.uniform(low=10, high=20, size=5)
print(random_numbers)
Output
[13.45678901 19.23456789 10.12345678 15.98765432 11.34567890]
โš ๏ธ

Common Pitfalls

Common mistakes when using numpy.random.uniform include:

  • Setting low greater than high, which causes an error.
  • Forgetting that high is inclusive, so the output can reach high.
  • Not specifying size when multiple values are needed, resulting in a single float instead of an array.
python
import numpy as np

# Wrong: low > high
# np.random.uniform(low=5, high=3, size=3)  # This will raise an error

# Right:
values = np.random.uniform(low=3, high=5, size=3)
print(values)
Output
[3.45678901 4.12345678 3.98765432]
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
lowLower boundary of the output interval (inclusive)0.0
highUpper boundary of the output interval (inclusive)1.0
sizeOutput shape; None returns a single floatNone
โœ…

Key Takeaways

Use numpy.random.uniform(low, high, size) to generate uniform random numbers.
The output interval is [low, high], including both low and high.
Specify size to get multiple random numbers as an array.
Ensure low is less than high to avoid errors.
Without size, the function returns a single float.