askvity

How to Generate Random Float Numbers in Python?

Published in Python Programming 1 min read

You can generate random float numbers in Python using the random module. Here's how:

The primary way to generate a random float between 0.0 (inclusive) and 1.0 (exclusive) is using the random.random() function.

import random

random_float = random.random()
print(random_float)

This code will output a random floating-point number between 0.0 and 1.0.

Generating Random Floats Within a Specific Range

To generate random floats within a specific range, you can use the random.uniform(a, b) function. This function returns a random floating-point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

import random

random_float_range = random.uniform(1.0, 10.0)
print(random_float_range)

This will generate a random floating-point number between 1.0 and 10.0 (inclusive). You can also specify negative ranges.

Other Methods

While less common for directly generating random floats, other functions within the random module can be adapted:

  • random.triangular(low, high, mode): Returns a random floating point number N such that low <= N <= high and with the specified mode value.

In summary, the random.random() function is the simplest way to generate a random float between 0.0 and 1.0, while random.uniform(a, b) allows you to specify a range for the random float.

Related Articles