To generate a random float in between 0 and 1, the easiest way is with the random function from the Python random module.
import random
for x in range(0,3):
print(random.random())
#Output:
0.5766391709474086
0.6620907660748007
0.8046101146489392
You can also use the uniform() function from the Python random module.
import random
for x in range(0,3):
print(random.uniform(0,1))
#Output:
0.142756405376938
0.285772552410724
0.895316881379259
When working with data, it can be very useful to generate random numbers to be able to perform simulations or get a random sample of a dataset.
In Python, we can generate random numbers in a range easily. The Python random module has many useful functions for generating random numbers.
Generating a random number between 0 and 1 is easy in Python. We can use the uniform() function, or we can use the random() function.
The random() function generates a random floating point value between 0 and 1. This is equivalent to calling the random uniform() function with arguments 0 and 1.
Below is an example of how to use Python to generate random float numbers between 0 and 1.
import random
#Using random.random()
for x in range(0,3):
print(random.random())
#Output:
0.5766391709474086
0.6620907660748007
0.8046101146489392
#Using random.uniform()
for x in range(0,3):
print(random.uniform(0,1))
#Output:
0.11326338183229978
0.8906530419045259
0.2598350417177795
How to Generate a Random Number Between Two Numbers in Python
We can easily generate random numbers in a range in Python with the uniform() function. As we know, the uniform() function takes two arguments and generates a random float between those two numbers.
Let’s create a function which will generate n random numbers in a given range and return them to us in a list.
Below is an example function in Python of how to generate n random numbers in a given range.
import random
def generateRandoms(a,b,n):
randoms = []
for x in range(0,n):
randoms.append(random.uniform(a,b))
return randoms
print(generateRandoms(5,15,10))
print(generateRandoms(0,100,10))
print(generateRandoms(-10,10,5))
#Output:
[5.694571539295616, 14.65143087945124, 8.281951034270097, 9.552800183834222, 14.466527725743468, 12.855545768024342, 5.555004019113447, 8.23846086476679, 13.68178655008311, 10.432019541766108]
[17.40931698981202, 21.338856311069076, 81.04739184068349, 9.05982067050396, 25.965253423876998, 50.77186986051261, 40.83043370119282, 22.9420759218404, 33.659027718483536, 87.5366194347588]
[1.0188556575830319, -0.3497662400817916, 0.8251588612524436, 1.098639882273325, -7.640642426128304]
Hopefully this article has been useful for you to learn how to generate random floats between 0 and 1 with random.random() and random.uniform() in Python.