Random double between Double.MIN_VALUE and Double.

2020-04-30 02:08发布

问题:

Anyone got an idea of how to achieve this. I've tried the usual formula but I'm only getting positive numbers <= 10:

Double.MIN_VALUE + Math.random() * ((Double.MAX_VALUE - Double.MIN_VALUE) + 1)

回答1:

You could do this

private static final Random rand = new Random();

public static double getRandomDouble() {
    while(true) {
        double d = Double.longBitsToDouble(rand.nextLong());
        if (d < Double.POSITIVE_INFINITY && d > Double.NEGATIVE_INFINITY)
            return d;
    }
}

This will return any finite double with equal probability.

You can't just the the formula above as the (Double.MAX_VALUE - (-Double.MAX_VALUE)) overflows to infinity. i.e. the range for all positive and negative double values is too large to store in a double.



回答2:

double d = Math.random() * Double.MAX_VALUE;
return Math.random() < 0.5 ? d : 0-d;


标签: java random