The uniform() method in Python generates a random floating-point number within a specified range. It belongs to the random module and is commonly used when a continuous random number is needed. For example, suppose we need to generate a random float number between 1 to 10
import random
print(random.uniform(1,10))
Output
2.0014240090730393
Explanation: random.uniform(1,10) generates a random float number between 1 to 10 (inclusive).
Syntax of uniform() method
random.uniform(l, u)
Parameters
- l - lower bound (inclusive).
- u - upper bound (inclusive).
Return Type: uniform(l, u) returns a float value.
Examples of uniform() method
Example 1. Generate random number
Generating random float number using uniform() method.
import random
# initializing bounds
l = 6
u = 9
print(random.uniform(l, u))
Output
6.706427492848576
Explanation:
- import the random module before using the uniform method.
- random.uniform(l, u) will generate a radom float number between 'l' and 'u'.
Example 2. Generating Random Latitudes and Longitudes
.uniform() method can be used to generate random latitude and longitude coordinates, including negative floating-point values.
import random
lat = random.uniform(-90, 90)
lon = random.uniform(-180, 180)
print("Random Location: ",lat,",", lon)
Output
Random Location: 73.3285434510266 , -82.611145839544
Explanation:
- random.uniform(-90, 90) returns a latitude between -90 and 90 (inclusive).
- random.uniform(-180, 180) returns a longitude between -180 and 180 (inclusive).