使用Python的max()时的浮点精度 [英] Floating point precision while using Python's max()
本文介绍了使用Python的max()时的浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> max(2,2.01)
2.0099999999999998
解决方案
以二进制表示的数字为2.01:
b10.00000010100011111100001010001111110000101000111111000010100011111100 ...
计算机仅使用有限数量的数字来存储浮点值,但二进制表示2.01需要无限多个数字;结果,它是最接近的可表示的值:
b10.000000101000111111000010100011111100001010001111110
用十进制表示,这个数字正是:
2.0099999999999997868371792719699442386627197265625
打印出来时,时间到十七位数字,给:
2.0099999999999998
Why so?
>>> max(2, 2.01)
2.0099999999999998
解决方案
The number 2.01 represented in binary is:
b10.00000010100011111100001010001111110000101000111111000010100011111100...
The computer uses only a finite number of digits to store floating-point values, but the binary representation of 2.01 requires infinitely many digits; as a result, it is rounded to the closest representable value:
b10.000000101000111111000010100011111100001010001111110
Expressed in decimal, this number is exactly:
2.0099999999999997868371792719699442386627197265625
When you print it out, it is rounded a second time to seventeen decimal digits, giving:
2.0099999999999998
这篇关于使用Python的max()时的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文