Eri*_*ric 5 python precision numpy
我为这个非常简单而愚蠢的问题道歉; 但是,为什么这两种情况的精确度有差异?
1)
>> test = numpy.array([0.22])
>> test2 = test[0] * 2
>> test2
0.44
Run Code Online (Sandbox Code Playgroud)
2)
>> test = numpy.array([0.24])
>> test2 = test[0] * 2
>> test2
0.47999999999999998
Run Code Online (Sandbox Code Playgroud)
我在64位linux上使用python2.6.6.预先感谢您的帮助.
这似乎也适用于python中的列表
>>> t = [0.22]
>>> t
[0.22]
>>> t = [0.24]
>>> t
[0.23999999999999999]
Run Code Online (Sandbox Code Playgroud)
因为它们是不同的数字,不同的数字具有不同的舍入效果.
(实际上,右侧的任何相关问题都将解释舍入效应本身的原因.)
好的,更严肃的回答.似乎numpy对数组中的数字执行一些转换或计算:
>>> t = numpy.array([0.22])
>>> t[0]
0.22
>>> t = numpy.array([0.24])
>>> t[0]
0.23999999999999999
Run Code Online (Sandbox Code Playgroud)
而Python不会自动执行此操作:
>>> t = 0.22
>>> t
0.22
>>> t = 0.24
>>> t
0.24
Run Code Online (Sandbox Code Playgroud)
舍入误差小于numpy的"eps"值float,这意味着它应该被视为相等(事实上,它是):
>>> abs(numpy.array([0.24])[0] - 0.24) < numpy.finfo(float).eps
True
>>> numpy.array([0.24])[0] == 0.24
True
Run Code Online (Sandbox Code Playgroud)
但是Python将它显示为'0.24'并且numpy不是因为Python的默认float.__repr__方法使用较低的精度(IIRC,这是最近的变化):
>>> str(numpy.array([0.24])[0])
0.24
>>> '%0.17f' % 0.24
'0.23999999999999999'
Run Code Online (Sandbox Code Playgroud)