How to generate random double number outside a specified range in Java?

831 Views Asked by At

Is there a way to generate random double value outside a specified range?

I know there is one within the range:

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

I would require one that is outside the range e.g

the range is 20 - 50 and I would like a number below 20 or higher than 50.

Could someone please advise?

4

There are 4 best solutions below

1
On BEST ANSWER

You can try somethink like this :

Random rnd = new Random();
double x=0;
do{
    x = rnd.nextDouble()*100;
}while(x>20 && x<50 );

    System.out.println(x);
    }

You generate a random double ( need multiply by 100 because generate double return value between 0 and 1 ) and loop while result >20 and <50

3
On

If you want a double, any double, outside a specific range, then you you can take advantage of the fact that a double is represented by 64 bits, and you can convert any 64-bit value to a double using the Double.longBitsToDouble method:

public static void main(String[] args) {
    Random r = new Random();

    double d;
    do {
        d = Double.longBitsToDouble(r.nextLong());
    } while (d >= 20 && d <= 50);

    System.out.println(d);
}
0
On

Maybe something like (for numbers 1-20 and 50-100):

Random r = new Random();
double randomValue = r.nextDouble()*70;
if(randomValue>20) randomValue+=30;

It is not resource expensive and easy to understand.

2
On

First of all you always need some upper bound for the number you're generating, so 'above rangeMax' won't really do. What you basically want is to have a number generated that falls into one of two ranges [0,minRange] or [maxRange, maxValue].

You can either go with the 'lazy approach' which is just generating a value between 0 and maxValue and generate a new one until you get on that does not fall into the [minRange,maxRange] range or you could do a two step generation process, i.e. generate a random number that determines whether you generate a number in the lower range or the upper range, for instance:

public static void main(String[] args) {
    double result  = (new Random().nextInt(2)) == 0 ? generateInRange(0, 20) : generateInRange(50, Double.MAX_VALUE);
}

private static double generateInRange(double min, double max) {
    return new Random().nextDouble() * (max-min) + min;
}

This does give you a 50/50 chance of ending up in the lower and upper range, so you might want to tweak that.