numpy:矩阵逆计算不正确?

时间:2018-09-05 01:23:05

标签: python-3.x numpy

我有一个值的矩阵key_class

[[17, 17, 5], [21, 18, 21], [2, 2, 19]]

我正在尝试使用以下代码计算其逆:

key_class = [[17, 17, 5],
             [21, 18, 21],
             [2, 2, 19]]

import sys 
key_class = np.array(key_class)
print ("Class key:")
print (key_class)

# Check if matrix is singular
if np.linalg.cond(key_class) < 1/sys.float_info.epsilon:
    print ("Inverse exists")
    key_class_inverse = np.linalg.inv(key_class)
else:
    print ("Inverse does not exist")

key_class_mul = np.floor(np.matmul(key_class, key_class_inverse))

print ("Class inverse:")
print (key_class_inverse)
print ("Multiplicative Inverse:")
print (key_class_mul)

以下是输出:

Class key:
[[17 17  5]
 [21 18 21]
 [ 2  2 19]]
Inverse exists
Class inverse:
[[-3.19488818e-01  3.33333333e-01 -2.84345048e-01]
 [ 3.80191693e-01 -3.33333333e-01  2.68370607e-01]
 [-6.38977636e-03  2.11344372e-18  5.43130990e-02]]
Multiplicative Inverse:
[[ 1. -1.  0.]
 [ 0.  1.  0.]
 [-1.  0.  0.]]

输出应该是一个单位矩阵,不是这种情况。怎么了?

1 个答案:

答案 0 :(得分:1)

>>> np.round(key_class_inverse@key_class,1) # works 
array([[ 1.,  0.,  0.],
       [ 0.,  1., -0.],
       [ 0.,  0.,  1.]])

>>> np.floor(key_class_inverse@key_class) # does not work 
array([[ 1.,  0.,  0.],
       [ 0.,  1., -1.],
       [ 0.,  0.,  0.]])

>>> np.floor(key_class@key_class_inverse) # also does not work 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [-1.,  0.,  0.]])

您只是误解了np.floor。其他一切都很好。