Usage
The uniform()
method generates a random floating-point number within a specified range. This range includes both the lower bound and the upper bound.
This method follows a uniform distribution, meaning that any number within the specified range has an equal chance of being generated.
The generated random numbers are not truly random in a cryptographic sense but are pseudorandom, which means they are generated using an algorithm with deterministic behavior based on the initial seed. If you need cryptographically secure random numbers, you should use the secrets module.
Syntax
random.uniform(a, b)
Parameters
Parameter | Condition | Description |
a | Required | A number (a float or an integer) specifying the lowest possible outcome. |
b | Required | A number (a float or an integer) specifying the highest possible outcome. |
Return Value
- The
uniform()
method returns a floating point numberN
, such thata <= N <= b
fora <= b
andb <= N <= a
forb < a
. - The
uniform()
method generates a random float between a and b using the equationa + (b-a) * random()
. Due to floating-point rounding, the end-point value b may or may not be included in the range.
Module Import
To use the uniform()
method, you need to import the random module first.
import random
Examples
Here’s a variety of examples to illustrate how you can use the uniform()
method.
# Get a random float number between 1 and 10
print(random.uniform(1, 10))
# Possible output: 8.77786425542658
# Get a random float number between -10 and 10
print(random.uniform(-10, 10))
# Possible output: -1.6196726867798645
Even if you swap the order of a
and b
, the uniform()
method will still work.
# The following two calls are equivalent
print(random.uniform(1, 10))
print(random.uniform(10, 1))
Controlling Random Number Generation with a Seed
The uniform()
method generates pseudo-random floating-point numbers. While they seem random, these numbers are produced by a deterministic algorithm that starts with an initial value called a “seed.” This means if you use the same seed, the sequence of generated “random” numbers will be identical each time.
Let’s see how you can control this randomness using random.seed():
import random
# Set seed for repeatability
random.seed(5)
# Print a random float number between 1 and 10
print(random.uniform(1, 10))
# Possible output: 6.606115254007317
If you run this block of code again, you will get the same result.
print(random.uniform(1, 10))
# Output: 6.606115254007317
Using consistent seeds is very helpful during debugging, as it lets you isolate issues by reproducing the exact same random behavior. It’s also valuable when you need your results to be replicable, like in certain simulations or experiments.