javaapachematrixapache-commonsapache-commons-math

Apache Commons Math: Eigendecomposition of a tridiagonal matrix yields wrong result


I am trying to find the diagonal matrix D of eigenvalues and matrix V whose columns are the corresponding right eigenvectors (where AV = VD) of the tri diagonal matrix J. I’m attempting to implement existing MATLAB code in java however the result I am getting in java is dissimilar to that in MATLAB (the MATLAB result being the correct result). I have created a folder on google drive of the matrices from MATALB and java so you can see the differences.

Variables

Java Code Snippet:

    RealMatrix J2 = new Array2DRowRealMatrix(j);
    EigenDecomposition eig = new EigenDecomposition(J2);
    RealMatrix V = eig.getV();
    RealMatrix D = eig.getD();

Apache Documentation

MATLAB Code:

[V,D]=eig(J);

MATLAB Documentation

Here are the matrices for each variable:

Variable J:

J

Variable V:

Expected:

V Expected

Actual: V Actual

Variable D:

Expected:

D Expected

Actual: D Actual


Solution

  • You can't say in this case that one result is correct and one is wrong as the results from Apache Commons Math and MATLAB are actually equivalent. Keep in mind that:

    1. In both cases you can print results with specific accuracy. If you truncate 0.5045259791 to 5 decimal digits you get 0.50452. Same result.
    2. You can multiple an eigenvector with any scalar including -1 and the result will also be an eigenvector. That's because the set of eigenvectors is linear subspace and is closed under scalar multiplication read on Wikipedia. Note that the first actual eigenvector is the last expected multiplied by -1
    3. Different implementations of eigen decomposition use different conventions for the ordering of eigenvalues in the result. The actual D seems to have the reverse order than the expected one.
    4. The machine epsilon i.e. upper bound on the relative error due to rounding in floating point arithmetic for a double precision floating point number is 2.22e-16. You can see seemingly big differences between actual and expected results for numbers close to machine epsilon. That is to be expected for 2 different eigen decomposition implementations.