How can I generate a random double in Java?
All tutorials only show how to generate in a certain range, but I want all doubles possible.
Is there something which just shuffles all bits and gives me the number?
How can I generate a random double in Java?
All tutorials only show how to generate in a certain range, but I want all doubles possible.
Is there something which just shuffles all bits and gives me the number?
What you can do is generate a random 64-bit value. This can give you Not-A-Number and +/-Infinity.
Random rand = new Random();
double d = Double.longBitsToDouble(rand.nextLong());
Note: Random only produces 2^48 possible long
values. You can use SecureRandom to generate all possible 64-bit values but this is much slower.
In terms of real numbers, your rand is [-Double.MAX_VALUE, Double.MAX_VALUE] The distribution is even for all possible representations.
You have about 1/4096 chance of having a NaN. You could loop this operation to discard any undesirable values.
Numbers are big. If there theoretically existed a way to generate a random number from among "all" numbers, there's a 99.99999....% chance that the number would be larger that anything representable in memory, even if you had every atom in the universe as memory.
You have to choose a range, period.