(Rcpp)armadillos abs() function outputs false values when used with c++ double while std::abs works

  armadillo, c++, r, rcpp, rcpparmadillo

Consider this R function:

r_abs <- function(x,y,z){
    2 * abs((x >= y) - z)
}

And those 2 RcppArmadillo equivalents:

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(RcppProgress)]]
#include <RcppArmadillo.h>
#include <string>
#include <progress.hpp>
using namespace arma;

// [[Rcpp::export]]
double arma_abs(const double &x, const double &y, const double &z)
{
    return 2 * abs((x >= y) - z);
}

// [[Rcpp::export]]
double std_abs(const double &x, const double &y, const double &z)
{
    return 2 * std::abs((x >= y) - z);
}

Now here is the problem:

sourceCpp(".test/test.cpp")

x <- 1
y <- 2
z <- 0.5

r_abs(x,y,z)
[1] 1
arma_abs(x, y, z)
[1] 0
std_abs(x, y, z)
[1] 1

Why does arma_abs() output 0 here? The problem only occurs for -1 < z < 1.

I really appreciate any help you can provide.

Source: Windows Questions C++

LEAVE A COMMENT