How to generate random float in range with Numpy?

Learn how to generate random floating-point numbers in a specified range using NumPy’s random.uniform() function for creating random float arrays.

Numpy random float array

How to Generate Random Float Values Using np.random.uniform()

Use np.random.uniform(low, high, size) to generate random float values uniformly distributed between low (inclusive) and high (exclusive).

import numpy as np

my_array = np.random.uniform(-1, 0, 50).reshape(5, -1)
print(f"My array: \n {np.round(my_array, 2)}")

np.random.uniform(-1, 0, 50) generates 50 random floats uniformly distributed between -1 (inclusive) and 0 (exclusive), NOT between -1 and 2.

See also  How to shuffle an array in Numpy?

The np.round(array, 2) function rounds all elements to 2 decimal places for display; this is optional and doesn’t affect the underlying values.