What is the best way to generate a random float value included into a specified value interval?


I want to generate a random float value in Java. The value has to be within a specific range of possible values.

For example, I have to generate a random value that is in the following range:

MIN: 41,815080
MAX: 41,829191

These values happen to represent a range of possible longitudes on a map, but the question applies more generally.

What is a smart way to do it?


Answers:


For a random value within a range, the formula is:

double random = min + Math.random() * (max - min);

This basic formula is constant no matter what you use to generate random numbers.

Math.random() provides moderately well distributed numbers, but you can replace it with whatever random number generator you want, for example (slightly better):

Random r = new Random();
double random = min + r.nextDouble() * (max - min);

or if you really want a float:

float random = min + r.nextFloat() * (max - min);

Or you can a more exotic 3rd party library.