w3resource

NumPy: Generate a random number between 0 and 1


Generate Random Number [0,1]

Write a NumPy program to generate a random number between 0 and 1.

This NumPy program generates a random number between 0 and 1. By utilizing NumPy's random number generation functions, it efficiently produces a floating-point number within the specified range. This program demonstrates the ease of generating random values using NumPy's built-in capabilities.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Generating a random number from a normal distribution with mean 0 and standard deviation 1 using np.random.normal()
rand_num = np.random.normal(0, 1, 1)

# Printing a message indicating a random number between 0 and 1
print("Random number between 0 and 1:")

# Printing the generated random number
print(rand_num)

Output:

Random number between 0 and 1:
[-1.15262276]                         

Explanation:

In the said code -

The np.random.normal() function generates a random number from a normal distribution with a mean (loc) of 0 and a standard deviation (scale) of 1. The third argument, 1, specifies the number of random numbers to generate, which is a single number in this case.

Finally print(rand_num) prints the generated random number to the console. The output will vary each time the code is executed due to the random nature of the function.

Visual Presentation:

NumPy: Generate a random number between 0 and 1.

Python-Numpy Code Editor: