Python random.uniform() function


The random.uniform() function in Python is part of the built-in random module, and it is used to generate a random floating-point number within a specified range. Unlike random.randint(), which returns integers, random.uniform() returns a float that can be either greater than or less than the specified bounds.

Syntax

import random random_float = random.uniform(a, b)
  • Parameters:
    • a: The lower bound of the range (can be any float).
    • b: The upper bound of the range (can be any float).

Return Value

  • Returns a random float NN such that a≤N≤ba \leq N \leq b if a<ba < b, or b≤N≤ab \leq N \leq a if b<ab < a.

Example Usage

  1. Basic Example:

    import random random_float = random.uniform(1.0, 10.0) # Random float between 1.0 and 10.0 print(random_float) # Example output: 6.23741098850783
  2. Generating Multiple Random Floats: You can generate multiple random floats using a loop:

    for _ in range(5): print(random.uniform(5.0, 15.0)) # Random float between 5.0 and 15.0

    This could output something like:

    11.285455204164003 7.187957800678712 12.141405165649837 8.927038204140303 14.209638145231943
  3. Using with Other Functions: You can use random.uniform() in calculations:

    a = random.uniform(1, 5) b = random.uniform(1, 5) result = a + b # Adding two random floats print("Sum of random floats:", result)
  4. Seeding the Random Number Generator: You can use random.seed() to initialize the random number generator for reproducibility:

    random.seed(42) # Seed the random number generator print(random.uniform(1, 10)) # Output will be the same each time the seed is set

Summary

  • random.uniform(a, b) generates a random floating-point number within the range [a,b][a, b] (inclusive).
  • It is useful in simulations, modeling, and any situation requiring random float values, especially when precise decimal values are needed.
  • The ability to seed the random number generator allows for reproducibility, which can be beneficial in testing and debugging scenarios.