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

DDD
Release: 2024-10-18 18:37:29
Original
329 people have browsed it

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

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

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!

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!