开发者

Loss of precision with very small numbers in Python arrays

I have two arrays in float64 type and when I assign the value of the first to the second it rounds the value. The following simple code illustrates the problem and excludes the possibility of just a mere number representation thing. (I've schematized a fragment of my code to be more readable, but it is in essence the same thing)

X = zeros((2,2))
Y = zeros((2,2))
Z = X            #a shorter way of making a new matrix, equal to X...
X[0,0] = Y[0,0]
Z[0,0]=0
print Y[0,0]
print X[0,0]
print type(Y[0,0])
print type(X[0,0])
if X[0,0]==Y[0,0]:
   print'they开发者_StackOverflow are equal'
else:
   print'they are NOT equal'

I ran this little snippet of code for all coefficients and all the outputs are similar to this:

1.90897e-14
0
<type 'numpy.float64'>
<type 'numpy.float64'>
they are NOT equal

It seems to me that the X array is of another type, but it's created in the same way, with the zeros() function with the standard type (float64)

Edit: The arrays are initialized with

X = zeros((2,2), dtype=float64)
Y = zeros((2,2), dtype=float64)

Also included an additional useful print in the example above.

Edit: added the problematic lines, after I found the problem


Are you absolutely certain that X is a float64 array? If it were, I'd expect X[0,0] to be 0.0, but you see 0 instead, which looks to me like an integer..

>>> Xf = arange(10,dtype=float64)
>>> Xi = arange(10)
>>> Xf[0]
0.0
>>> Xi[0]
0
>>> Yf = Xf*0.0
>>> Yf[0]
0.0
>>> 
>>> Yf[0] = 1.90897e-14
>>> Yf[0]
1.9089700000000001e-14
>>> Xf[0] = Yf[0]
>>> Xf[0]
1.9089700000000001e-14
>>> Xi[0] = Yf[0]
>>> Xi[0]
0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜