科学记数法会影响 Perl 的精度吗?
我在 Perl 中遇到了一个奇怪的行为。下面的减法应该产生零结果(Python 中就是这样):
print 7.6178E-01 - 0.76178
-1.11022302462516e-16
为什么会发生这种情况以及如何避免它?
PS 效果出现在“为 x86_64-linux-gnu-thread-multi 构建的 v5.10.0”(Ubuntu 9.04) 和“为 darwin-2level 构建的 v5.8.9”(Mac OS 10.6) 上
I encountered a weird behaviour in Perl. The following subtraction should yield zero as result (which it does in Python):
print 7.6178E-01 - 0.76178
-1.11022302462516e-16
Why does it occur and how to avoid it?
P.S. Effect appears on "v5.10.0 built for x86_64-linux-gnu-thread-multi" (Ubuntu 9.04) and "v5.8.9 built for darwin-2level" (Mac OS 10.6)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并不是科学计数法对精度的影响如此之大,而是二进制表示的浮点计数法的局限性。请参阅 perlfaq4 的答案。对于任何依赖底层架构进行数字存储的语言来说,这都是一个问题。
如果你需要更好的数字处理,请查看 bignum 编译指示。
It's not that scientific notation affects the precision so much as the limitations of floating point notation represented in binary. See the answers to the perlfaq4. This is a problem for any language that relies on the underlying architecture for number storage.
If you need better number handling, check out the bignum pragma.