gpt4 book ai didi

javascript - 在使用 `Math.random()` 时,我是否应该考虑 2^62 中有 1 种可能性获得排除的上限?

转载 作者:数据小太阳 更新时间:2023-10-29 04:12:53 25 4
gpt4 key购买 nike

来自 MDN(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random):

Math.random

Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

但是,它说:

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for Math.random() itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 2^62) to calculate the usually-excluded upper bound.

我应该考虑这些情况吗?例如,使用...

Math.min(max, Math.floor(Math.random() * (max - min + 1)) + min);

...而不是...

Math.floor(Math.random() * (max - min + 1)) + min;

...?

最佳答案

如果您每秒调用 Math.random() 十亿 次,您应该预计每 150 年左右就会遇到此错误。我对 Javascript 方式 的性能评价过高。 :-)

关于javascript - 在使用 `Math.random()` 时,我是否应该考虑 2^62 中有 1 种可能性获得排除的上限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com