Python数组中非常小的数字会导致精度损失 [英] Loss of precision with very small numbers in Python arrays

查看:221
本文介绍了Python数组中非常小的数字会导致精度损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个float64类型的数组,当我将第一个的值分配给第二个时,它会四舍五入.以下简单代码说明了该问题,并排除了仅使用数字表示的可能性. (我已经对代码片段进行了图解说明,以提高可读性,但这本质上是同一件事)

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 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

在我看来,X数组是另一种类型,但是它是以相同的方式创建的,其标准类型为(float64)的zeros()函数

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)

数组用初始化

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

在上面的示例中还包括一个附加的有用打印内容.

Also included an additional useful print in the example above.

发现问题后,添加了有问题的行

added the problematic lines, after I found the problem

推荐答案

您是否完全确定 X是float64数组?如果是这样,我希望X [0,0]为0.0,但是您看到的却是0,在我看来,它就像一个整数.

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

这篇关于Python数组中非常小的数字会导致精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆