Python数组中的浮点精度 [英] Floating point precision in Python array
问题描述
对于这个非常简单而愚蠢的问题,我深表歉意.但是,为什么在这两种情况下显示的精度有所不同?
I apologize for the really simple and dumb question; however, why is there a difference in precision displayed for these two cases?
1)
>> test = numpy.array([0.22])
>> test2 = test[0] * 2
>> test2
0.44
2)
>> test = numpy.array([0.24])
>> test2 = test[0] * 2
>> test2
0.47999999999999998
我在64位linux上使用python2.6.6. 预先感谢您的帮助.
I'm using python2.6.6 on 64-bit linux. Thank you in advance for your help.
这似乎也适用于python中的列表
This also hold seems to hold for a list in python
>>> t = [0.22]
>>> t
[0.22]
>>> t = [0.24]
>>> t
[0.23999999999999999]
推荐答案
因为它们是不同的数字,并且不同的数字具有不同的舍入效果.
Because they are different numbers and different numbers have different rounding effects.
(实际上,右侧的所有相关问题"都将解释舍入效应本身的原因.)
(Practically any of the Related questions down the right-hand side will explain the cause of the rounding effects themselves.)
好的,更严肃的答案.看来numpy对数组中的数字执行了一些转换或计算:
Okay, more serious answer. It appears that numpy performs some transformation or calculation on the numbers in an array:
>>> t = numpy.array([0.22])
>>> t[0]
0.22
>>> t = numpy.array([0.24])
>>> t[0]
0.23999999999999999
Python不会自动执行此操作:
whereas Python doesn't automatically do this:
>>> t = 0.22
>>> t
0.22
>>> t = 0.24
>>> t
0.24
舍入误差小于float
的numpy的"eps"值,这意味着应将其视为相等(实际上是):
The rounding error is less than numpy's "eps" value for float
, which implies that it should be treated as equal (and in fact, it is):
>>> abs(numpy.array([0.24])[0] - 0.24) < numpy.finfo(float).eps
True
>>> numpy.array([0.24])[0] == 0.24
True
但是Python将其显示为'0.24'而不是numpy的原因不是因为Python的默认float.__repr__
方法使用了较低的精度(这是IIRC,这是最近的更改):
But the reason that Python displays it as '0.24' and numpy doesn't is because Python's default float.__repr__
method uses lower precision (which, IIRC, was a pretty recent change):
>>> str(numpy.array([0.24])[0])
0.24
>>> '%0.17f' % 0.24
'0.23999999999999999'
这篇关于Python数组中的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!