This practical article shows you 3 different ways to generate a random floating point number in a given range between a min
value and a max
value. All of these approaches are quick and simple. Let’s get started.
Using random.uniform()
The uniform()
function from the random
module produces a random floating number between the two specified numbers (both included). Below is the syntax:
random_float = random.uniform(min, max)
Example:
import random
x = random.uniform(1.05, 11.05)
print(x)
Output:
9.117390934888798
If you want to get a result with only 2 or 3 decimals, you can use the round()
function, like so:
import random
# 2 decimals
print(round(random.uniform(1.05, 11.05), 2))
# 3 decimals
print(round(random.uniform(4.5, 4.9), 3))
Output:
1.59
4.691
In case you want to get the same result each time the code executes, just set a random seed
like this:
import random
random.seed(5)
print(round(random.uniform(1.05, 11.05), 2))
print(round(random.uniform(4.5, 4.9), 3))
Using random.random()
The random()
function returns a random float between 0 (inclusive) and 1 (exclusive). Instead of getting the result in the range 0 – 1, you can get a result in the range min - max
as shown below:
result = (max - min) * random.random() + min
Example:
import random
min = 1.05
max = 11.05
x = (max - min) * random.random() + min
# Print out the random float
print(x)
# Print out the random float rounded to 2 decimal places
print(round(x, 2))
Output:
4.922380391899899
4.92
Using random.triangular()
The syntax:
random_float = random.triangular(min, max, mode)
The triangular()
function creates a random float between min
and max
(both included), but you can also specify a third parameter, the mode
parameter. This parameter helps you weigh the possible outcome closer to one of the bounds. By default, mode
is to the midpoint between the two bounds, which will not weigh the possible outcome in any direction.
Example:
import random
x = random.triangular(0.1, 9.9)
print(x)
Output:
3.5215390121917745
In this example, the result will be most likely closer to the lower bound:
import random
x = random.triangular(2.1, 9.9, mode=3)
print(x)
That’s it, buddy. Happy coding & have a nice day!