Home  >  Article  >  Java  >  How to Generate Random Doubles within a Specified Range in Java?

How to Generate Random Doubles within a Specified Range in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 01:43:27532browse

How to Generate Random Doubles within a Specified Range in Java?

Generating Random Doubles within a Specified Range

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.

Generating Random Doubles with Boundaries

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.

Modifying the Range of Random Doubles

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.

Example Implementation

<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!

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