Home >Backend Development >Python Tutorial >How to Generate Random Floating-Point Values Within a Range in Python?

How to Generate Random Floating-Point Values Within a Range in Python?

DDD
DDDOriginal
2024-10-18 18:37:29451browse

How to Generate Random Floating-Point Values Within a Range in Python?

Accessing Random Values within a Float Range

While the random.randrange(start, stop) function is a versatile tool for generating random integers, it falls short when attempting to obtain random values within a float range. To bridge this gap, python incorporates the random.uniform(a, b) function.

Utilizing random.uniform

To generate random floating-point numbers within a specified range, invoke random.uniform(a, b) with the following syntax:

random.uniform(start, end)

Here, start represents the lower bound of the desired range, and end denotes the upper bound. The resulting random number will fall somewhere between these two values.

Example:

Consider the task of obtaining a random number between 1.5 and 1.9. Using random.uniform, this can be effortlessly accomplished as shown below:

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

When executed, this code will print a random floating-point number within the specified range.

Additional Notes:

  • random.uniform generates numbers with uniform distribution, meaning that all values within the specified range are equally likely to be selected.
  • random.uniform allows start and end to be swapped without affecting the functionality, since the random number is uniformly distributed.
  • The returned value is of the float data type, even if the input values are integers.

The above is the detailed content of How to Generate Random Floating-Point Values Within a 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