本文介绍了Double.MIN_VALUE和Double.MAX_VALUE之间是否是随机的两倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都知道如何实现这一目标.我已经尝试了通常的公式,但是我只得到正数< = 10:
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)
推荐答案
您可以这样做
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;
}
}
这将以相等的概率返回任何有限的double.
This will return any finite double with equal probability.
随着(Double.MAX_VALUE - (-Double.MAX_VALUE))
溢出到无穷大,您不能只是上面的公式.即所有正负双精度值的范围都太大,无法存储为双精度值.
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.
这篇关于Double.MIN_VALUE和Double.MAX_VALUE之间是否是随机的两倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!