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)]
Why am I getting all those decimals? Is there a way to make the numpy floats behave like python floats?
EDIT:
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
解决方案
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
The same problem probably triggered a previous question. Personally, I consider this a bug in numpy.