I'm trying to create a Linear Discriminant Analysis in Java (mostly by hand) and comparing the results with numpy
module in Python. In some part of the algorithm, it requires the inverse of a matrix. For that, I'm using org.apache.commons.math3.linear
package in Java and numpy.linalg
package in Python.
At some point, the inverse of the following matrix needs to be solved:
[[ 0.325, -0.045, 0.02 , 0.18 ],
[-0.045, 0.405, 0.18 , 0.18 ],
[ 0.02 , 0.18 , 0.085, 0.105],
[ 0.18 , 0.18 , 0.105, 0.205]]
In Python:
import numpy as np
M = np.array([[ 0.325, -0.045, 0.02, 0.18],
[-0.045, 0.405, 0.18, 0.18],
[ 0.02, 0.18, 0.085, 0.105],
[ 0.18, 0.18, 0.105, 0.205]])
print(np.linalg.inv(M))
The output is:
array([[ 1.97032484e+16, 1.87649984e+14, 4.50359963e+16, -4.05323966e+16],
[ 8.19404932e+15, -6.42874947e+15, 3.70295969e+16, -2.05163983e+16],
[ 2.25179981e+16, 1.85147985e+16, -0.00000000e+00, -3.60287970e+16],
[-3.60287970e+16, -4.00319967e+15, -7.20575940e+16, 7.20575940e+16]])
In Java:
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
double[][] m = {{ 0.325, -0.045, 0.02, 0.18},
{-0.045, 0.405, 0.18, 0.18},
{ 0.02, 0.18, 0.085, 0.105},
{ 0.18, 0.18, 0.105, 0.205}};
RealMatrix rm = new Array2DRowRealMatrix(m);
System.out.println(new LUDecomposition(rm).getSolver().getInverse());
But it throws the following exception:
org.apache.commons.math3.linear.SingularMatrixException: matrix is singular
I've tried to use another library, like Jama
, but it still throws the same error:
import Jama.Matrix;
double[][] m = {{ 0.325, -0.045, 0.02, 0.18},
{-0.045, 0.405, 0.18, 0.18},
{ 0.02, 0.18, 0.085, 0.105},
{ 0.18, 0.18, 0.105, 0.205}};
Matrix m0 = new Matrix(m);
Matrix mi = jm.inverse();
mi.print(5, 3);
My questions are:
Why I can solve the inverse of this matrix in Python but not in Java?
According to Wikipedia, a singular matrix is a square matrix which is not invertible, so why is Python able to invert the matrix if, according to Java, the matrix is not inversible?
Thanks in advance!