I'm trying to convert some algorithms from Matlab to Python 3.8. In the algorithm I'm trying to inverse some matrix, the result is that Matlab inverse the matrix as it should do but Python (using numpy.linalg) says that it cannot inverse singular matrix. After some debugging, we found out that in Matlab the determinant of the matrix was 5.79913020654461e-35 but in python, it was 0. Thanks a lot!
Im using Python 3.8 with numpy version 1.20.0 and Matlab 2017a
This is the data:
My matrix:
[[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.]]
My Python script:
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}")
Output of Python script:
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 script + output:
>> 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
Alredy tried to use other data types but with no success