任何人都知道如何实现这一目标。我已经尝试了通常的公式,但我只得到正数 <= 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 。
您不能只使用上面的公式,因为 (Double.MAX_VALUE - (-Double.MAX_VALUE))
会溢出到无穷大。即所有正 double 值和负 double 值的范围太大而无法存储在 double 值中。
关于java - Double.MIN_VALUE 和 Double.MAX_VALUE 之间的随机 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60955253/