In Java, it's often necessary to generate random numbers within a specified range for various applications. For instance, in simulations or games, you might need to create random values within a specific interval.
The standard library provides the Random class for generating random numbers. However, it can only generate random doubles between 0.0 (inclusive) and 1.0 (exclusive). To generate random doubles within a different range, we need to apply some transformations.
Suppose we have two doubles min and max representing the desired range. To generate a random double between min and max, we can use the following formula:
<code class="java">double randomValue = min + (max - min) * r.nextDouble();</code>
where r is an instance of the Random class. By multiplying the result of r.nextDouble() by the difference between max and min, we shift the range to start from min and modify the scale to fit within the desired interval. Subsequently, adding min to this value yields the final random double within the specified range.
<code class="java">import java.util.Random; public class RandomDoubleRange { public static void main(String[] args) { double min = 100.0; double max = 101.0; Random r = new Random(); double randomValue = min + (max - min) * r.nextDouble(); // Output the generated random double System.out.println("Random Double: " + randomValue); } }</code>
By running this code, you'll obtain a random double value that lies between 100.0 and 101.0 inclusive. This approach provides a flexible way to generate random doubles within any desired range.
The above is the detailed content of How to Generate Random Doubles within a Specified Range in Java?. For more information, please follow other related articles on the PHP Chinese website!