numpy数组中有多余的小数? [英] extra decimals in numpy array?
问题描述
假设我有一个浮点列表和一个要压缩的numpy数组:
Let's say I have one list of floats and a numpy array that I wish to zip:
>>> import numpy as np
>>> n1 = [0.9, 1.1]
>>> n2 = np.array([0.9,1.1])
>>> zip(n1,n2)
[(0.9, 0.90000000000000002), (1.1, 1.1000000000000001)]
为什么我会得到所有这些小数?有没有一种方法可以使numpy浮点数的行为像python浮点数一样?
Why am I getting all those decimals? Is there a way to make the numpy floats behave like python floats?
似乎计算也受numpy存储浮动方式的影响:
It seems that calculations are also affected by the way numpy stores floats:
>>> nb1 = n2[1]+0.1
>>> nb1
1.2000000000000002
>>> nb2 = nb1 - 1.2 #nb2 should be equal to 0
2.2204460492503131e-16
>>> nb3 = np.asscalar(nb2)
>>> nb3
2.2204460492503131e-16 #nb3 should be equal to 0
>>> type(nb3)
float
推荐答案
python浮点数和numpy数组都可能是64位浮点数,但它们被封装"在不同的对象中.差异可能是由于python浮点数和numpy浮点数的repr
不同.
Both the python floats and the numpy arrays are probably 64-bit floating point numbers, but they are 'encapsulated' in different objects. The difference is probably due to different repr
for python floats and numpy floats.
In [12]: n1[0]
Out[12]: 0.9
In [13]: n2[0]
Out[13]: 0.90000000000000002
In [14]: n1[0] == n2[0]
Out[14]: True
In [15]: type(n1[0])
Out[15]: float
In [16]: type(n2[0])
Out[16]: numpy.float64
同一问题可能触发了上一个问题.我个人认为这是numpy中的错误.
The same problem probably triggered a previous question. Personally, I consider this a bug in numpy.
这篇关于numpy数组中有多余的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!