Coding Ref

How to use numpy.random.uniform() in Python

How to use numpy.random.uniform() in Python

numpy.random.uniform() is a function in the Python numpy library that generates random numbers from a uniform distribution.

A uniform distribution is a distribution where all values have an equal probability of being drawn from the distribution.

Syntax

The syntax for numpy.random.uniform() is as follows:

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

Here, low is the lower bound of the interval from which the random numbers will be drawn, high is the upper bound of the interval, and size is the number of random numbers to generate.

All of these parameters are optional, with default values of 0.0 for low, 1.0 for high, and None for size.

Examples

Here are some examples of using numpy.random.uniform():

main.py
import numpy as np

# Generate 10 random numbers from a uniform distribution
# between 0 and 1 (the default range)
np.random.uniform(size=10)

# Generate 5 random numbers from a uniform distribution
# between 10 and 20
np.random.uniform(low=10, high=20, size=5)

# Generate 3 random numbers from a uniform distribution
# between -5 and 5
np.random.uniform(low=-5, high=5, size=3)

In each of these examples, numpy.random.uniform() generates random numbers from a uniform distribution within the specified range and returns them as a numpy array.

The array will have the specified number of elements, as determined by the size parameter.

You'll also like

Related tutorials curated for you

    What does numpy.arrange() do?

    How to use numpy.zeros() in Python

    How to use numpy.ravel() in Python

    How to use numpy.ndarray.flatten() in Python

    How to use numpy.clip() in Python

    How to use numpy.linspace() in Python

    NumPy numpy.transpose()

    NumPy: np.arrange()

    How to use numpy.exp() in Python

    How to use numpy.round() in Python

    How to use numpy.random.uniform() in Python

    ModuleNotFoundError: No module named 'numpy' in Python