1

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!

  • 2
    Does this answer your question? [numpy.linalg.inv returns inverse for a singular matrix](https://stackoverflow.com/questions/46126739/numpy-linalg-inv-returns-inverse-for-a-singular-matrix) – Edeki Okoh Feb 04 '20 at 21:17
  • Matrix is singular: https://www.wolframalpha.com/input/?i=det%28%5B%5B+0.325%2C+-0.045%2C++0.02%2C++0.18%5D%2C+++++++++++++++%5B-0.045%2C++0.405%2C++0.18%2C++0.18%5D%2C+++++++++++++++%5B++0.02%2C+++0.18%2C+0.085%2C+0.105%5D%2C+++++++++++++++%5B++0.18%2C+++0.18%2C+0.105%2C+0.205%5D%5D%29 – Johannes Kuhn Feb 04 '20 at 21:19

0 Answers0