为什么浮点数和双精度数的计算会出现错误?
我一直想知道为什么当计算机应该给出精确的答案时浮点数却不太准确。我在一本书中读到,最好将变量与我们想要的值周围的数字进行比较,因为计算值可能并不总是像我们期望的那样是整数。机器如何计算这些除法?欢迎任何网站链接:)
I always wondered why the floats aren't really acurate when computers should give the precise answer. I read in a book somewhere that it is better to compare a variable to a number around the value we want, since the calculate value may not always be a whole number as we expect. How do machines caluclate these divisions? Any links to websites are welcome :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Jon Skeet 在这里提到了这一点(向下滚动直到看到幻灯片上绘制的“double d=0.3;”):
http://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka- humanity-epic-fail.aspx
这里有更详细的答案:
http://download.oracle.com/docs/cd /E19957-01/806-3568/ncg_goldberg.html
Jon Skeet mentions it here (scroll down till you see "double d=0.3;" drawn on a slide):
http://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx
A more detailed answer here:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
一个简单的答案是计算机使用有限数量的数字来表示数字。
如果你尝试用十进制表示数字 1/7,它将是 0.14285714...等等。
计算机也会发生同样的情况,即尝试用二进制表示数字 1/10(十进制的 0.1),这也成为无限级数。
因此有时您无法获得最准确的数字。
a simple answer would be that a computer uses a limited amount of digits to represent a number.
If you try to represent i.e. the number 1/7 in decimal it would be 0.14285714... and so on infinitely.
The same happens for computer i.e. trying to represent the number 1/10 (0.1 in decimal) in binary which becomes an infinite series as-well.
Therefor sometimes you don't get the most accurate number.