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

DDD
Release: 2024-10-18 18:30:29
Original
333 people have browsed it

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>
Copy after login

Syntax:

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

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!