Python

How to Generate a Random Number Between 0 and 1 in Python

By ayed_amira , on 08/20/2021 , 1 comment - 3 minutes to read
python generate random number

We will see in this article how to generate a random number between 0 and 1 in python

Introduction

  • randrange(): this method returns a random number within a range.
  • random(): returns a floating-point number between 0 and 1.
  • uniform(): returns a floating-point random number between two given parameters.
  • Using numpy random.uniform()

Python generate random number

Generate Random Number Using randrange()

# randrange()

import random          
print(random.randrange(0,1))

This function will always return the value 0 because the return value is always an integer. We will see later on other methods that allow to return floats.

Generate Random Number Using random()

# random() 

import random
for i in range(0, 1):
    print("Number generated: %s " % random.random())

Number generated: 0.4923345546583948 

We see that the function has generated a number between 0 and 1. Here we use a loop to specify on which interval we must generate our number.

Generate Random Number Using uniform()

# uniform() 

import random
print("Number generated: %s " % random.uniform(0, 1)) 

This will generate a floating-point random number between 0 and 1 at each execution.

You can generate a large number of random numbers and store them in a list to see the distribution of the random numbers generated.


import random
import matplotlib.pyplot as plt

list_random = [random.uniform(0, 1) for i in range(1000)]
plt.hist(list_random, density=1)
plt.show()
generate random number between 0 and 1 python
Generation of 1000 random numbers

We can see that the distribution of each value obtained is not totally uniform.

Generate Random Number Using numpy random.uniform()

# using numpy module 

import numpy as np

r_number = np.random.uniform(0, 1)
print(r_number)

>>> 0.15335820879348916

We can see that the function has generated a random number between 0 and 1. It is possible to modify the interval, for example to obtain a number between 0 and 100.

Conclusion

We have seen in this tutorial that there are many methods to generate a random number between 0 and 1. These methods are widely used by programmers. These functions also allow you to generate a number on an interval defined by yourself which gives you the possibility to modify it according to your needs.

I hope this tutorial has helped you to understand better how to generate a random number. Anyway, I’m still available if you have any questions about this subject!

See you soon.

Back to Python Menu

ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Comments

Leave a comment

Your comment will be revised by the site if needed.