Home > Java > javaTutorial > body text

How to Generate Random Doubles Within a Specific Range in Java?

Barbara Streisand
Release: 2024-10-26 09:01:03
Original
568 people have browsed it

How to Generate Random Doubles Within a Specific Range in Java?

Generating Random Doubles Within a Specified Range

When dealing with double values, it often becomes necessary to generate random values within a predefined range. While the Random class provides the nextDouble() method, it doesn't allow for specifying a range.

Customizing Double Generation

To achieve random double generation within a range, we can utilize the following formula:

<code class="java">rangeMin + (rangeMax - rangeMin) * r.nextDouble()</code>
Copy after login

where:

  • rangeMin represents the minimum value of the desired range.
  • rangeMax represents the maximum value of the desired range.
  • r is an instance of the Random class.

Example Usage

Suppose we have two doubles min = 100 and max = 101. To generate a random double within this range, use the following code:

<code class="java">Random r = new Random();
double randomValue = 100 + (101 - 100) * r.nextDouble();</code>
Copy after login

This calculation ensures that the generated random value falls between 100 (inclusive) and 101 (exclusive).

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

source:php.cn
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
Latest Articles by Author
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!