How do I implement a function getRandomDouble(min,max)
which is able to handle +-Double.MAX_VALUE
as parameter?
Online Research:
Most answers to this question are:
public Double getRandomDouble(double min, double max) {
return min + (max-min)*Random.nextDouble();
}
This works fine if min
and max
are not +-Double.MAX_VALUE
. If so, max-min
is out of range or infinity. Changing the parameters to BigDecimal
solves this issue, but the result is always a double with 50 zeros and no decimals. This is the result of a very large number (2*MAX_VALUE
) multiplied a double between [0,1] with only a view decimals.
So, I found a solution for +-MAX_VALUE
like this:
public double getRandomDouble() {
while(true) {
double d = Double.longBitsToDouble(Random.nextLong());
if (d < Double.POSITIVE_INFINITY && d > Double.NEGATIVE_INFINITY)
return d;
}
}
This works fine, but does not consider other bounds.
How can I combine both approaches to get random double in a given range that's maybe +-MAX_VALUE
?