Last modified: Jan 10, 2023 By Alexander Williams

3 Methods to random number between 0 and 1 in Python

Python programming has many built-function and methods to generate numbers.
This tutorial will show three methods to random a member between 0 and 1.

1. random.random()

random() is a method of random() that returns a floating-point number between 0 and 1.

Syntax

random.random()

Example

import random

# Get a random number between 0 and 1
rd = random.random()

print(rd)

Output:

0.5396613726896038

As you can see, the 0.5396613726896038 number is between 0 and 1.

We'll print two decimal places of our number in the following example:

# Print 2 decimal places of a number.
n  = "{:.2f}".format(rd)
print(n)

Output:

0.54

2. random.uniform()

uniform() is a method that returns a random floating number between two given numbers. We can use this method to get a random number between 0 and 1.

Syntax

random.uniform(a, b)

Example

import random

# Get a random number between 0 and 1
rd = random.uniform(0, 1)

print(rd)

Here, we have set 0 and 1 in the uniform's parameter, which means the random number will be between 0 and 1.

Output:

0.8360711852906063

3. np.random.random()

np.random.random() is a method of NumPy that returns a random floating number by a given size. By default, the method return one random number.

Let's see how to use it to get a random number between 0 and 1.

Syntax

random.random(size=None)

By default Example

import numpy as np

# Random number
rd = np.random.random()

print(rd)

Output:

0.36613218384578594

It will return 5 random numbers in the following example:

import numpy as np

# 5 Random numbers
rd = np.random.random(5)

print(rd)

Output:

[0.25336161 0.87962794 0.41721669 0.48175205 0.90389224]