Home  >  Article  >  Java  >  How to Generate a Random Double Within a Specified Range in Programming?

How to Generate a Random Double Within a Specified Range in Programming?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 18:32:03798browse

How to Generate a Random Double Within a Specified Range in Programming?

Generating a Random Double Within a Specified Range

In programming, it's often necessary to generate random values within a specific range. This is typically achieved using a random number generator that returns values between 0 and 1. However, if you have specific minimum and maximum values, you may need to adjust the output accordingly.

Consider the following situation: You have two double values, min and max, and you want to generate a random double between those two values. The following code only generates a random double between 0 and 1:

Random r = new Random();
r.nextDouble();

To specify the range, you need to perform some additional calculations:

Random r = new Random();
double rangeMin = 100;
double rangeMax = 101;
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();

Here's how this code works:

  • The Random object r generates a random double between 0 and 1.
  • The randomValue variable is calculated by adding the rangeMin value to the difference between rangeMax and rangeMin multiplied by the randomly generated double.

This calculation effectively shifts the range of the generated value to be within the specified bounds. Therefore, randomValue will be a random double between rangeMin and rangeMax.

The above is the detailed content of How to Generate a Random Double Within a Specified Range in Programming?. 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