# 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();
r.nextDouble();
``````

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

To generate a random value between `rangeMin` and `rangeMax`:

``````Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
``````
• This is generally correct, but beware of its limits. If you do `double rangeMax= Double.MAX_VALUE;` and `double rangeMin= -rangeMax;` you will always get an infinite value in return. You might want to check for `Double.valueOf(rangeMax-rangeMin).isInfinite()`.
– lre
Apr 7, 2014 at 10:55
• Note that the results of this will often exclude many double values in the desired range, if that range is larger than 0.0-1.0. If the desired range contains a larger number of values than the range 0.0-1.0 there will not be a value for each of them and they will never get generated. (By the pigeonhole principle!). Because of this Tunaki's solution is better.
– Lii
Jun 17, 2018 at 12:38
• @Lii there will not be a value for each of them why not? Aug 20, 2019 at 0:47
• @K_7: Say for example that there are 10,000 distinct double value between 0.0 and 1.0 (in reality there are probably more). But if the range between `rangeMin`and `rangeMax` is large, then there might be 10,000,000 distinct double values between them. The result of `(rangeMax - rangeMin) * r.nextDouble()` will only choose between 10,000 of those possible 10,000,000 values. (I feel that this is not a perfect explanation, but maybe it helps a little bit...)
– Lii
Aug 20, 2019 at 7:25
• Ah I see. Basically, multiplying a number that can take a finite set of values doesn't change the size of that set. Aug 22, 2019 at 14:27

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`.

• call requires api 21 Feb 1, 2017 at 10:25
• @XarEAhmer What's API 21? Mar 4, 2019 at 5:44
• Looks like he's referring to Android. Aug 20, 2019 at 0:45

Use this:

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

EDIT:

`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.
}
}
``````

Hope, this might help the best : Random Number Generators in Java

## Sharing a Complete Program:

``````import java.util.Random;

public class SecondSplitExample
{
public static void main(String []arguments)
{
int minValue = 20, maxValue=20000;
Random theRandom = new Random();
double theRandomValue = 0.0;

// Checking for a valid range-
if( Double.valueOf(maxValue - minValue).isInfinite() == false )
theRandomValue = minValue + (maxValue - minValue) * theRandom.nextDouble();

System.out.println("Double Random Number between ("+ minValue +","+ maxValue +") = "+ theRandomValue);
}
}
``````

Here is the output of 3 runs:

``````Code>java SecondSplitExample
Double Random Number between (20,20000) = 2808.2426532469476

Code>java SecondSplitExample
Double Random Number between (20,20000) = 1929.557668284786

Code>java SecondSplitExample
Double Random Number between (20,20000) = 13254.575289900251
``````

``````Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
``````
• I like how this could reduce a parameter (versus having a min and max, just have an interval) Aug 2, 2020 at 15:03

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 (https://docs.oracle.com/javase/8/docs/api/java/util/Random.html)

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)
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://stackoverflow.com/questions/3680637/generate-a-random-double-in-a-range/32808589", "fetch_time": 1660109793000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2022-33/segments/1659882571147.84/warc/CC-MAIN-20220810040253-20220810070253-00761.warc.gz", "warc_record_offset": 502496133, "warc_record_length": 69908, "token_count": 1573, "char_count": 5771, "score": 3.578125, "int_score": 4, "crawl": "CC-MAIN-2022-33", "snapshot_type": "longest", "language": "en", "language_score": 0.8743181824684143, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00041-of-00064.parquet"}