Generate a random double in a range


I have two doubles like the following

double min = 100;
double max = 101;

and with a random generator, I need to create a double value between the range of min and max.

Random r = new Random();

but there is nothing here where we can specify the range.

9/27/2015 7:41:26 PM

This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:

double random = ThreadLocalRandom.current().nextDouble(min, max);

nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int, and can be double.


Use this:

double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));


new Random().nextDouble(): randomly generates a number between 0 and 1.

start: start number, to shift number "to the right"

end - start: interval. Random gives you from 0% to 100% of this number, because random gives you a number from 0 to 1.

EDIT 2: Tks @daniel and @aaa bbb. My first answer was wrong.


import java.util.Random;

public class MyClass {
     public static void main(String args[]) {
          Double min = 0.0;  // Set To Your Desired Min Value
          Double max = 10.0; // Set To Your Desired Max Value
          double x = (Math.random() * ((max - min) + 1)) + min;   // This Will Create A Random Number Inbetween Your Min And Max.
          double xrounded = Math.round(x * 100.0) / 100.0;   // Creates Answer To The Nearest 100 th, You Can Modify This To Change How It Rounds.
          System.out.println(xrounded);    // This Will Now Print Out The Rounded, Random Number.

Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {

The main idea of random is that it returns a pseudorandom value. There is no such thing as fully random functions, hence, 2 Random instances using the same seed will return the same value in certain conditions.

It is a good practice to first view the function doc in order to understand it (

Now that we understand that the returned value of the function nextDouble() is a pseudorandom value between 0.0 and 1.0 we can use it to our advantage.

For creating a random number between A and B givin' that the boundaries are valid (A>B) we need to: 1. find the range between A and B so we can know how to many "steps" we have. 2. use the random function to determine how many steps to take (because the returned value is between 0.0 and 1.0 you can think of it as "pick a random percentage of increase" 3. add the offset

After all of that, you can see that mob gave you the easiest and most common way to do so in my opinion

double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();

double RandomValue = Offset + (Range)*(randomVal between 0.0-1.0)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]