问题描述
我们可以使用下面列出的函数轻松获得所需范围内的随机浮点数 [X,Y)
(注意 X 是包含的,Y 是不包含的),因为 Math.random()
(以及大多数伪随机数生成器,AFAIK)在 [0,1)
中产生数字:
We can easily get random floating point numbers within a desired range [X,Y)
(note that X is inclusive and Y is exclusive) with the function listed below since Math.random()
(and most pseudorandom number generators, AFAIK) produce numbers in [0,1)
:
function randomInRange(min, max) {
return Math.random() * (max-min) + min;
}
// Notice that we can get "min" exactly but never "max".
我们如何获得一个期望范围内的随机数包括到两个边界,即[X,Y]
?
How can we get a random number in a desired range inclusive to both bounds, i.e. [X,Y]
?
我想我们可以通过滚动"一个 IEE-754 浮点双精度 将最大可能值准确地设置为 1.0 但这似乎很难做到正确,尤其是在不适合的语言中位操作.有没有更简单的方法?
I suppose we could "increment" our value from Math.random()
(or equivalent) by "rolling" the bits of an IEE-754 floating point double precision to put the maximum possible value at 1.0 exactly but that seems like a pain to get right, especially in languages poorly suited for bit manipulation. Is there an easier way?
(顺便说一句,为什么随机数生成器在 [0,1)
而不是 [0,1]
中生成数字?)
(As an aside, why do random number generators produce numbers in [0,1)
instead of [0,1]
?)
请注意,我没有需要这个,我完全知道这种区别是迂腐的.只是好奇并希望得到一些有趣的答案.如果这个问题不合适,请随时投票结束.
Please note that I have no need for this and I am fully aware that the distinction is pedantic. Just being curious and hoping for some interesting answers. Feel free to vote to close if this question is inappropriate.
推荐答案
我相信有更好的决定,但这个应该可行 :)
I believe there is much better decision but this one should work :)
function randomInRange(min, max) {
return Math.random() < 0.5 ? ((1-Math.random()) * (max-min) + min) : (Math.random() * (max-min) + min);
}
这篇关于包含范围内的随机浮点双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!