'Numpy adds extra decimals on conversion
I noticed when converting from numpy array to list that python adds extra decimals. For example here I have some bytes that I convert to a numpy array with float32 elements:
import numpy as np
b = bytes([174, 153, 92, 59])
a = np.frombuffer(b, dtype=np.float32)
print(a[0])
print(a.tolist()[0])
Output:
0.0033660936
0.0033660936169326305
On the conversion with a.tolist() it adds extra decimals.
What is happening here? Do I loose some precision, or where is python finding these extra decimals?
Solution 1:[1]
with .tolist you change the datatype from float32 to float. Check:
import numpy as np
b = bytes([174, 153, 92, 59])
a = np.frombuffer(b, dtype=np.float32)
a = np.array(a, dtype=np.float)
print(a[0])
print(a.tolist()[0])
Solution 2:[2]
try print out their type
print(type(a[0])) # numpy.float32
print(type(a.tolist()[0])) # float
when you call tolist(), it changes numpy scalars to Python scalars. Python default float is float64, which is the same as numpy.float64. That's why the second one shows extra decimals.
If you try a = np.frombuffer(b, dtype=np.float64), and then call tolist(), two values should be the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kilian |
| Solution 2 | CJR |
