我正在尝试将一些算法从 Matlab 转换为 Python 3.8。在算法中,我试图反转一些矩阵,结果是Matlab按照它应该做的那样反转矩阵,但Python(使用numpy.linalg)说它不能反转奇异矩阵。
经过一番调试,我们发现在Matlab中矩阵的行列式是5.79913020654461e-35,但在python中却是0。
多谢!
我使用Python 3.8和numpy版本1.20.0和Matlab 2017a
这是数据:
我的矩阵:
[[3.0322662511118286, 3.645196880210743, 1.3326781661192055, -4.925254309001175],
[3.645196880210743, 4.382022947889959, 1.6020606012651588, -5.920826258432845],
[1.3326781661192055, 1.6020606012651588, 0.5857108009982133, -2.164644637608797],
[-4.925254309001175, -5.920826258432845, -2.164644637608797, 8.]]
我的Python脚本:
import numpy as np
np.set_printoptions(20) # Matrix dtype is float 64, meaning that there will be up to 15 digits after decimal point
matrix = np.array([[3.0322662511118286, 3.645196880210743, 1.3326781661192055, -4.925254309001175],
[3.645196880210743, 4.382022947889959, 1.6020606012651588, -5.920826258432845],
[1.3326781661192055, 1.6020606012651588, 0.5857108009982133, -2.164644637608797],
[-4.925254309001175, -5.920826258432845, -2.164644637608797, 8.]])
print(f"Matrix is: {matrix}")
print(f"dtype is: {matrix.dtype}")
print(f"Matrix det is: {np.linalg.det(matrix)}")
try:
print(f"Inverse matrix is: {np.linalg.inv(matrix)}")
except np.linalg.LinAlgError as e:
print(f"Failed to inverse matrix. Error code: '{e}")
Python 脚本的输出:
Matrix is: [[ 3.0322662511118286 3.645196880210743 1.3326781661192055
-4.925254309001175 ]
[ 3.645196880210743 4.382022947889959 1.6020606012651588
-5.920826258432845 ]
[ 1.3326781661192055 1.6020606012651588 0.5857108009982133
-2.164644637608797 ]
[-4.925254309001175 -5.920826258432845 -2.164644637608797
8. ]]
dtype is: float64
Matrix det is: 0.0
Failed to inverse matrix. Error code: 'Singular matrix
Matlab脚本+输出:
>> format longg
>> matrix =
3.0322662511118286 3.645196880210743 1.3326781661192055 -4.925254309001175
3.645196880210743 4.382022947889959 1.6020606012651588 -5.920826258432845
1.3326781661192055 1.6020606012651588 .5857108009982133 -2.164644637608797
-4.925254309001175 -5.920826258432845 -2.164644637608797 8.
>> det (matrix)
ans = 5.79913020654461e-35
>> inv (matrix)
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.480881e-17.
ans =
463831092542248 557587200641207 203852870968935 753391506264877
557587200641207 670315847520521 245068621497740 905696113927055
203852870968935 245068621497740 89607103131709.8 331125436963685
753391506264877 905696113927055 331125436963685 1.2237353746994e+15
已经尝试使用其他数据类型但没有成功