w3resource

Mastering numpy.random.uniform for Random Data Sampling


Comprehensive Guide to numpy.random.uniform in Python

numpy.random.uniform is a powerful NumPy function used to generate random numbers uniformly distributed over a specified range. This function is often utilized in simulations, data sampling, and Monte Carlo methods, where evenly distributed random values are required.


Syntax:

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

Parameters:

  • low (float, optional): The lower bound of the range (inclusive). Default is 0.0.
  • high (float, optional): The upper bound of the range (exclusive). Default is 1.0.
  • size (int or tuple of ints, optional): The number of random values to generate. If None, a single float is returned. Otherwise, an array is returned with the specified shape.

Returns:

  • ndarray or float: Random values sampled uniformly from the specified range.

Examples:

Example 1: Generate a single random number between 0 and 1

Code:

import numpy as np

# Generate a random number between 0 and 1
random_number = np.random.uniform()

print("Random number between 0 and 1:", random_number)

Output:

Random number between 0 and 1: 0.683358279889759

Explanation:

This generates a single random float value uniformly distributed between 0 (inclusive) and 1 (exclusive).


Example 2: Generate random numbers in a specific range

Code:

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 between 10 and 20:", random_numbers)

Output:

Random numbers between 10 and 20: [18.39186033 10.77866027 17.16653293 16.54400256 12.31002177]

Explanation:

Here, the range is set from 10 (inclusive) to 20 (exclusive), and five random numbers are generated in this range.


Example 3: Create a 2D array of random numbers

Code:

import numpy as np

# Create a 2x3 array of random numbers between -5 and 5
random_array = np.random.uniform(low=-5, high=5, size=(2, 3))

print("2D array of random numbers between -5 and 5:")
print(random_array)

Output:

2D array of random numbers between -5 and 5:
[[ 4.90728954 -3.940697    3.002603  ]
 [-3.50622153 -4.6393456   3.90870081]]

Explanation:

A 2x3 array is generated, with each element uniformly sampled between -5 and 5.


Additional Notes:

  • Reproducibility: To ensure consistent results across runs, use numpy.random.seed().
  • Code:

    np.random.seed(42)
  • Performance: NumPy's random.uniform is optimized for large-scale computations and can generate large arrays efficiently.
  • Applications: Frequently used in machine learning for initializing weights, statistical sampling, and algorithm testing.

Practical Guides to NumPy Snippets and Examples.



Follow us on Facebook and Twitter for latest update.