在Python数组中使用非常小的数字丢失精度

Die*_*ego 5 python numpy

我有两个float64类型的数组,当我将第一个值分配给第二个时,它会舍入值.以下简单的代码说明了问题,并排除了仅仅编号表示事物的可能性.(我已经将我的代码片段架构为更具可读性,但它本质上是相同的东西)

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'
Run Code Online (Sandbox Code Playgroud)

我为所有系数运行了这段代码,所有输出都类似于:

1.90897e-14
0
<type 'numpy.float64'>
<type 'numpy.float64'>
they are NOT equal
Run Code Online (Sandbox Code Playgroud)

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

编辑:使用初始化数组

X = zeros((2,2), dtype=float64)
Y = zeros((2,2), dtype=float64)
Run Code Online (Sandbox Code Playgroud)

还包括上述示例中的其他有用打印件.

编辑:在我发现问题后添加了有问题的行

DSM*_*DSM 3

绝对确定X 是 float64 数组吗?如果是的话,我希望 X[0,0] 为 0.0,但你看到的是 0,在我看来它像一个整数。

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • @Diego:我更多地思考的是,你拥有的 X 并不是你认为你拥有的那个。 (2认同)