How to Generate Random Number Between 0 and 1 in Python

Here are ways to generate random numbers between 0 and 1 in Python:

  1. Using random.random()
  2. Using random.uniform()
  3. Using numpy.random.random()
  4. Using random.randint()

Method 1: Using random.random()

The random.random() method generates a float number between 0.0 and 1.0 (inclusive of 0.0 and exclusive of 1.0).

It does not accept any parameter.

Visual RepresentationVisual Representation of Generate Random Number Between 0 and 1 in Python using random.uniform()

Example

import random

print("Random number between 0 and 1:", random.random())

Output

Random number between 0 and 1: 0.13804061085976338

Method 2: Using random.uniform()

The random.uniform() method generates a random floating-point number between two specified values.

Visual RepresentationVisual Representation of Using random.uniform()

Example

import random

print("Random number between 0 and 1:", random.uniform(0, 1))

Output

0.6895695527148721

Method 3: Using numpy.random.random() 

The np.random.random() method returns a single float when called without any arguments.

Visual Representation

Visual Representation of Using numpy.random.random()

Example

import numpy as np 

print("Random number between 0 and 1:", np.random.random())

Output

Random number between 0 and 1: 0.49303392090458364

Method 4: Using random.randint()

The random.randint() method returns a random integer value within the specified range. So in our case, it can return either 0 or 1.

Visual Representation

Visual Representation of Using random.randint()

Example

import random

print("Random number 0 or 1:", random.randint(0, 1))

Output

Random number 0 or 1: 1

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.