Python random.random() function


The random.random() function in Python is part of the built-in random module, and it generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). This function is often used when you need a random value in that specific range, which is particularly useful in simulations, games, and randomized algorithms.

Syntax

import random random_float = random.random()

Return Value

  • Returns a random float NN such that 0.0≤N<1.00.0 \leq N < 1.0.

Example Usage

  1. Basic Example:

    import random random_float = random.random() print(random_float) # Example output: 0.37444887175646646
  2. Generating Multiple Random Floats: You can generate multiple random floats using a loop:

    for _ in range(5): print(random.random())

    This could output something like:

    0.9507143064099162 0.7319939418114051 0.5986584841970366 0.15601864044243635 0.15599452033620265
  3. Using with Other Random Functions: The output of random.random() can be combined with other functions to scale it into different ranges. For example, to get a random float between 10 and 20:

    scaled_random_float = 10 + (random.random() * 10) # 10 to 20 print(scaled_random_float)
  4. Seeding the Random Number Generator: You can use random.seed() to initialize the random number generator for reproducibility:

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

Summary

  • random.random() is a simple and effective way to generate random floating-point numbers in the range [0.0,1.0)[0.0, 1.0).
  • It is widely used in various applications requiring randomness, such as simulations, games, and statistical sampling.
  • For more complex random number generation (e.g., specific ranges or distributions), it can be combined with other functions in the random module.