Reputation: 304
I am using Rcpp
to integrate a piece of C++
code in R
. I am implementing a function in C++
in two ways:
// [[Rcpp::export]]
double rhobiweight(double x,double k = 2.0){
double rho = 1.0;
if(abs(x)<k){
rho = 1.0-pow((1.0-pow(x/k,2)),3);
}
return rho/Erho(k) ;
}
// [[Rcpp::export]]
double rhobiweight2(double x,double k = 2.0){
double rho = 1.0-pow((1.0-pow(x/k,2)),3);
if(abs(x)>k){
rho = 1.0;
}
return rho/Erho(k) ;
}
If the x
-value is between 2 and 3, I get different results of these functions. I can't figure out why.
> set.seed(1)
> x = 3*rnorm(10^5)
> c = x
> c2 = x
> for(i in 1:length(x)){
+ c[i] = rhobiweight(x[i])
+ c2[i] = rhobiweight2(x[i])
+ }
> print(sum(c-c2))
[1] -18564.31
Upvotes: 3
Views: 111
Reputation: 8066
The problem comes from your if
statement inside the function. The negative of <
is >=
. so you should either replace <
with <=
in one function or >
with >=
in the other, depending on the expected behaviour.
Your problem happens for value between 2.0 and 2.9 inclusive because the abs(int)
will always return 2
for this range.
abs(x)
takes an int
an return an int
. Your double x
is implicitly conversion to an int
in your case.
Upvotes: 2