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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 09:01:03644browse

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>

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>

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!

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