Here are ways to generate random numbers between 0 and 1 in Python:
- Using random.random()
- Using random.uniform()
- Using numpy.random.random()
- 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 Representation
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 Representation
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
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
Example
import random
print("Random number 0 or 1:", random.randint(0, 1))
Output
Random number 0 or 1: 1
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.