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.
To achieve random double generation within a range, we can utilize the following formula:
<code class="java">rangeMin + (rangeMax - rangeMin) * r.nextDouble()</code>
where:
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!