w3resource

NumPy: Generate a random number between 0 and 1

NumPy: Basic Exercise-17 with Solution

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

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)

Sample 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.

Pictorial Presentation:

NumPy: Generate a random number between 0 and 1.

Python-Numpy Code Editor:

Previous: NumPy program to create a 3x3 identity matrix.
Next: NumPy program to generate an array of 15 random numbers from a standard normal distribution.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.