与浮点运算一致的整数除法
我需要在 JavaScript 中进行整数除法,这仅提供双精度浮点数可供使用。通常我只会执行 Math.floor(a / b) (或 a / b | 0
) 并完成它,但在这种情况下我正在进行模拟同步执行,并且需要确保机器和运行时之间的一致性,无论它们使用 64 位还是 80 位内部精度。
到目前为止,我还没有发现任何不一致的地方,但我无法最终说服自己它们不会发生。所以我想知道:
假设
a
和b
分别是0..2^31-1和1..2^31-1范围内的整数,JavaScriptMath.floor(a / b)
(和a / b | 0
)的结果是否保证在不同机器和运行时保持一致?为什么或为什么不?
I need to do integer division in JavaScript, which only gives me double-precision floating point numbers to work with. Normally I would just do Math.floor(a / b)
(or a / b | 0
) and be done with it, but in this case I'm doing simulation executed in lockstep and need to ensure consistency across machines and runtimes regardless of whether they use 64-bit or 80-bit internal precision.
I haven't noticed any inconsistencies so far, but I haven't been able to conclusively convince myself that they can't happen. So I'm left wondering:
Assuming
a
andb
are integers in range 0..2^31-1 and 1..2^31-1 respectively, are results from JavaScriptMath.floor(a / b)
(anda / b | 0
) guaranteed to be consistent across machines and runtimes?Why or why not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是不会。答案是它取决于许多因素:
ECMA 脚本的浏览器供应商实现。
特定版本的 ECMA 脚本是否指定该一致性级别(通常不指定)。
您可能不知道的最终用户计算机上的其他外部因素。
众所周知,浮点运算很容易出现舍入错误。虽然很高兴认为小数点右侧的所有数字都是准确的,但让两台运行截然不同的硬件和软件配置的机器就计算达成一致可能就像放牧猫一样。
My guess would be no. And the answer would be that it's dependent upon a number of factors:
Browser vendor implementations of ECMA Script.
Whether or not a particular version of ECMA Script specifies that level of consistency (typically not).
Other, external factors on the end-users' machines that you may not be aware of.
Floating point arithmetic is notoriously susceptible to rounding errors. While it's nice to think it's accurate with all those digits to the right-hand side of the decimal point, getting two machines running vastly different hardware and software configurations to agree on a calculation can be like herding cats.