在专属范围内产生随机双精度 [英] Generating a random double in an exclusive range

查看:67
本文介绍了在专属范围内产生随机双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在之间生成一个随机双精度值,但不包括它的下限和上限(下限,上限). 我已经看到了很多有关生成数字的问题,包括从下限到上限,但不包括上限(下限,上限),但是由于没有解决此问题,所以他们没有回答我的问题.

I'm trying to generate a random double between but not including it's lower and upper bound (lower, upper). I've seen a lot of questions about generating a number from, and including it's lower bound up to, but not including it's upper bound [lower, upper), but they don't answer my question as they do not address this case.

我已经为该问题提出了两个解决方案",但都不是很满意.

I've come up with two "solutions" to the problem, but am not really satisfied by either.

double myvalue;
do { myvalue = myrandom.nextDouble() * (upper - lower) + lower; } while (myvalue == lower);

尽管这几乎每次都会在第一次尝试时给出有效的结果,但它似乎不一致且笨拙,并且如果rng经常返回0.0,则效率也很低.

While this will almost everytime give a valid result on the first try it seems inconsistent and clunky, and on the off-chance that the rng returns 0.0 a lot, it's inefficient aswell.

double myvalue = 
0.5 * (1.0 + myrandom.nextDouble() - myrandom.nextDouble()) * (upper - lower) + lower;

尽管这将确保我第一次尝试时获得有效的号码,但在这种情况下,我认为分布并不均匀.

While this will guarantee me a valid number on the first try, I don't believe the distribution is uniform in this case.

谢谢

推荐答案

您的第一个代码非常正确.

Your first code is quite correct.

double myvalue;
do { 
    myvalue = myrandom.nextDouble() * (upper - lower) + lower; 
} while (myvalue == lower);  // Replace != with ==

只需将!=替换为==.效率低下是不正确的.

Simply replace != with ==. It is not true that this is not efficient.

对代码效率的了解.

看看nextDouble的代码,您会发现它是经过计算生成的随机long值.

Taking a look on the code of nextDouble you can see that it is calculated generating a random long value.

这意味着基本上您将有1种可能性在2 * 9,223,372,036,854,775,807(长值的范围减去1)上重复循环.

It means that basically you will have 1 possibility to repeat the loop over 2 * 9,223,372,036,854,775,807 (the range of long values minus 1).

附加说明:因为您使用的是double而不是BigDecimal,所以您可以获得的myvalue接近lower界限,但低于它,因此它最好将代码更改为排除小于lower 的值.它不会改变代码的效率.

Additional Note: because you are using double and not a BigDecimal you can obtain a myvalue that is close to the lower bound, but lower than it, so it is better to change the code to exclude also values lower than lower. It doesn't change the efficiency of your code.

double myvalue;
do { 
    myvalue = myrandom.nextDouble() * (upper - lower) + lower; 
} while (myvalue <= lower);  // Replace != with <=

这篇关于在专属范围内产生随机双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆