本文介绍了随机浮点双全纳范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以很容易地在所需范围内获得随机浮点数 [X,Y)(注意,X是包容性和Y是独享)用,因为下面列出的功能的Math.random()(和大多数伪随机数生成器,据我所知)产生号码[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]?

我想我们可以增量我们从值的Math.random()(或同等学历)由滚动的的把最大可能值正好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);
}

这篇关于随机浮点双全纳范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:09