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?
CodePudding user response:
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])
CodePudding user response:
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.
