替换 Numpy 数组的一部分时避免不正确的舍入

Avoid incorrect rounding when part of a Numpy Array is replaced

在我的代码的一部分中,我将以下代码与 numpy 数组一起使用:

import numpy as np

A=np.array([[1,-8],[2,-1],[2,14]])

k=2
x = np.array([[0],[15]])       

v=np.array([[1/np.sqrt(2)],[1/np.sqrt(2)]])

temp = x - 2*v @ v.T @ x

print("temp = ",temp)
I=np.array([[0,0],[0,0],[0,0]])
print("I = ",I)

I[k-1:3,k-1:2]= temp
print("new I =",I)

这是我看到的输出:

temp =  
[[-1.50000000e+01]
 [ 3.55271368e-15]]
I =  
[[0 0]
 [0 0]
 [0 0]]
new I = 
[[  0   0]
 [  0 -14]
 [  0   0]]

但是 -1.50000000e+01 = -15 所以我不确定为什么这个元素被替换为 -14。

如果我修改你的代码来创建 float dtype 数组,尤其是 I:

In [88]: A=np.array([[1,-8],[2,-1],[2,14]], float)    ###
    ...:  
    ...: k=2 
    ...: x = np.array([[0],[15]])        
    ...:  
    ...: v=np.array([[0.70710678],[0.70710678]]) 
    ...:  
    ...: temp = x - 2*v @ v.T @ x 
    ...:  
    ...: print("temp = ",temp) 
    ...: I=np.array([[0,0],[0,0],[0,0]], float)      ####
    ...: print("I = ",I) 
    ...:  
    ...: I[k-1:3,k-1:2]= temp 
    ...: print("new I =",I)                                                                    
temp =  [[-1.49999999e+01]
 [ 5.03409456e-08]]
I =  [[0. 0.]
 [0. 0.]
 [0. 0.]]
new I = [[ 0.00000000e+00  0.00000000e+00]
 [ 0.00000000e+00 -1.49999999e+01]
 [ 0.00000000e+00  5.03409456e-08]]

round 比截断给我更多的控制权:

In [90]: np.round(I)                                                                           
Out[90]: 
array([[  0.,   0.],
       [  0., -15.],
       [  0.,   0.]])
In [91]: I.astype(int)                                                                         
Out[91]: 
array([[  0,   0],
       [  0, -14],
       [  0,   0]])