Skip to content
Advertisement

How to find the inverse of a matrix using Apache Commons Math library in Java?

I’m trying to find the inverse of a matrix using the Apache Commons Math Library.

Below is my attempt at doing just that:

JavaScript

When I run this, I get the following error:

JavaScript

When I go to line 160 of FieldLUDecomposition.java per the above error message, I see that the library thinks this matrix is Singular i.e. it thinks it has no inverse:

JavaScript

However, doing a quick check on WolframAlpha shows that this matrix has a non-zero determinant and indeed has an inverse:

enter image description here

So the question is – what am I doing wrong and how do I find the inverse of my matrix? Am I using the wrong solver?

Advertisement

Answer

Below is based on apache common math 3.6.1

A ticket is raised concerning this issue, I submitted a patch to fix the problem and the fix version will be 4.0 (not yet released as of 2021-07-19)

The reason of issue is equals method in BigReal

JavaScript

where d is BigDecimal, the backing value of BigReal. This cause equals comparison return undesired result when two BigReal has d with same value but different scale, and cause error when initializing FieldLUDecomposition. For BigDecimal we should check

JavaScript

instead.

Solution:

  1. Check if workaround section(Copy BigReal as local class and change equals) helps.
  2. Wait for version 4.0 release.
  3. If double value matrix is acceptable, Use RealMatrix instead, and MatrixUtils provide handy inverse method
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement