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.

For more Practice: Solve these Related Problems:

  • Generate a random floating point number in [0,1) and round it to three decimals.
  • Create a function that returns five random numbers between 0 and 1.
  • Use np.random.random_sample to generate a single random value and display its type.
  • Generate a random number and check whether it is less than 0.5, then print a message.

Go to:


PREV : Create 3x3 Identity Matrix
NEXT : Generate Random Array from Standard Normal

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.