问题
I am assigning the elements of a numpy array to be equal to the subtraction of "small" valued, python float-type numbers. When I do this, and try to verify the results by printing to the command line, the array is reported as all zeros. Here is my code:
import numpy as np
np.set_printoptions(precision=20)
pc1x = float(-0.438765)
pc2x = float(-0.394747)
v1 = np.array([0,0,0])
v1[0] = pc1x-pc2x
print pc1x
print pc2x
print v1
The output looks like this:
-0.438765
-0.394747
[0 0 0]
I expected this for v1:
[-0.044018 0 0]
I am new to numpy, I admit, this may be an obvious mis-understanding of how numpy and float work. I thought that changing the numpy print options would fix, but no luck. Any help is great! Thanks!
回答1:
You're declaring the array with v1 = np.array([0,0,0])
, which numpy assumes you want an int array for. Any subsequent actions on it will maintain this int array status, so after adding your small number element wise, it casts back to int (resulting in all zeros). Declare it with
v1 = np.array([0,0,0],dtype=float)
There's a whole wealth of numpy specific/platform specific datatypes for numpy that are detailed in the dtype docs page.
回答2:
You are creating the array with an integer datatype (since you don't specify it, NumPy uses the type of the initial data you gave it). Make it a float:
>>> v1 = np.array([0,0,0], dtype=np.float)
>>> v1[0] = pc1x-pc2x
>>> print v1
[-0.04401800000000000157 0. 0. ]
Or change the incoming datatype:
>>> v1 = np.array([0.0, 0.0, 0.0])
>>> v1[0] = pc1x-pc2x
>>> print v1
[-0.04401800000000000157 0. 0. ]
来源:https://stackoverflow.com/questions/31732728/numpy-array-being-rounded-subtraction-of-small-floats