[英]how to get next random double on an open interval (x, y)
I know the basic algorithm for a random number in a half-closed interval is: 我知道半闭区间内随机数的基本算法是:
Random rand = new Random();
double increment = min + (max - min) * rand.nextDouble();
This will give you a random number on the interval [min, max)
because nextDouble
includes 0 in the range of results ( [0.0,1.0)
) that it returns. 这将在区间
[min, max)
上给出一个随机数[min, max)
因为nextDouble
在返回的结果范围( [0.0,1.0)
包含0。 Is there a good way to exclude the minimum value and instead provide a random number on (min, max)
? 有没有一种很好的方法可以排除最小值,而是在
(min, max)
上提供一个随机数?
In theory , calling Math.nextUp(double d)
should do it. 理论上 ,调用
Math.nextUp(double d)
应该这样做。
double minUp = Math.nextUp(min);
double increment = minUp + (max - minUp) * rand.nextDouble();
In reality, rounding after multiplication may still cause min
to be returned, so a retry loop would be better. 实际上,乘法后舍入可能仍会导致返回
min
,因此重试循环会更好。 Given the rarity of an exact min
value, performance won't suffer. 鉴于精确
min
的罕见性,性能不会受到影响。
double increment;
do {
increment = min + (max - min) * rand.nextDouble();
} while (increment <= min || increment >= max);
Just for heck of it, I also added a max
check. 只是为了它,我还添加了
max
支票。
Rather than asking for the minimum exclusively, you could ask for it inclusively -- but have the minimum be the next value of double using Math::nextUp
: 不是要求最低限度的最小值,而是可以包含它 - 但是使用
Math::nextUp
最小值是double的下一个值:
min = Math.nextUp(min);
Doubles are discrete, so this is analogous to in integer-land, rephrasing (0, 10)
as [1, 10)
. 双打是离散的,所以这类似于整数 - 土地,改述
(0, 10)
0,10 (0, 10)
为[1, 10)
1,10 [1, 10)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.