Home >Backend Development >Python Tutorial >How to Generate a Random Float Within a Given Range in Python?

How to Generate a Random Float Within a Given Range in Python?

DDD
DDDOriginal
2024-10-18 18:30:29516browse

How to Generate a Random Float Within a Given Range in Python?

How to Generate a Random Number within a Float Range

Question:

How can you generate a random number between two float values using the Python standard library?

Answer:

Unlike random.randrange(), which only accepts integer arguments, Python provides the random.uniform() function specifically designed to return a float value within a specified range.

Usage:

<code class="python">>>> import random
>>> random.uniform(1.5, 1.9)
1.8733202628557872</code>

Syntax:

<code class="python">random.uniform(a, b)</code>

where:

  • a: The lower bound of the range (inclusive)
  • b: The upper bound of the range (exclusive)

The random.uniform() function will generate a random float within the half-open range [a, b). For example, the code above will generate a random number between 1.5 and 1.9, inclusive of 1.5 but exclusive of 1.9.

The above is the detailed content of How to Generate a Random Float Within a Given Range in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn