I am trying to compute eigenvalues in C++ using the Armadillo function eig_sym via RcppArmadillo. The results are not entirely the same as the output of the R function eigen():

In R:

X=matrix(sample(1:25), 5)

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    7   18    4   19    6
#[2,]    9   22    3   25   16
#[3,]   14   12   24    8    2
#[4,]   20   11   21   23   15
#[5,]    5    1   13   10   17

#[1]  1.585160e+02  7.475128e+01  5.938207e+01  3.250609e+00 -4.293203e-15

In C++:

//--------------------------C++ Code ------------------------

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
arma::vec eigenval(arma::mat M) {
    arma::vec values=arma::eig_sym(M);
    return values;

I then compile the code in R using sourceCpp():

sort(as.vector(eigenval(Xcov)), TRUE)
#1.585160e+02 7.475128e+01 5.938207e+01 3.250609e+00 1.065789e-14

Compare the above results with the R function result (repeated below), we see that the last value is different.

#[1]  1.585160e+02  7.475128e+01  5.938207e+01  3.250609e+00 -4.293203e-15

Not sure if this is the right place to ask, but I wonder if anyone has any idea about the difference.

  • 3
    $\begingroup$ The last two numbers just look like numerical approximations of zero. My guess is you're dealing with nothing more than accumulated numerical error. I would have called those the same answer! $\endgroup$ – Glen_b May 20 '13 at 23:25

Numerical errors. The smallest eigenvalue is flirting with machine accuracy.

  • $\begingroup$ Does that mean if i want to keep my results consistent, I should just keep using one of the two methods. Eigenvalues are needed for an outlier detection method, but the different outputs from the two functions actually result in different outliers...so that's a bit unsettling... $\endgroup$ – Alex May 20 '13 at 21:40
  • 1
    $\begingroup$ Yes, probably. But be aware that neither solution is correct. In fact, I wouldn't know which one happens to be more accurate. It is not uncommon to discard/round up eigenvalues below a given threshold $t$ (for example $t=10^{-12}$. $\endgroup$ – Marc Claesen May 20 '13 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.