Home > Java > javaTutorial > body text

How Do You Generate a Random Double Within a Specific Range?

Linda Hamilton
Release: 2024-10-26 03:49:27
Original
588 people have browsed it

 How Do You Generate a Random Double Within a Specific Range?

Generating a Random Double within a Specified Range

When working with double values, it may be necessary to generate a random value within a specified range. To achieve this, there are two primary variables typically used: a minimum value (rangeMin) and a maximum value (rangeMax).

The default behavior of the nextDouble() method in the Random class creates a random double between 0.0 (inclusive) and 1.0 (exclusive). To adjust this range, we can use the formula:

randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
Copy after login

Here's a breakdown of the formula:

  • r.nextDouble(): Generates a random double between 0.0 and 1.0.
  • (rangeMax - rangeMin) * r.nextDouble(): Calculates a random value between 0.0 and (rangeMax - rangeMin).
  • rangeMin (rangeMax - rangeMin) * r.nextDouble(): Adds rangeMin to the calculated value, resulting in a random double between rangeMin and rangeMax.

For example, given rangeMin as 100.0 and rangeMax as 101.0:

Random r = new Random();
double randomValue = 100.0 + (101.0 - 100.0) * r.nextDouble();
Copy after login

This code will generate a random double between 100.0 and 101.0.

The above is the detailed content of How Do You Generate a Random Double Within a Specific Range?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template