[Rcpp-devel] A strange question while using Rcpp

晔张 zhangyet at gmail.com
Fri Jan 17 13:51:58 CET 2014


Dear all,

I have a strange question such that I can't conclude it in the title.
I have write an function:
//[[Rcpp::export]]
double mydcov(NumericVector x, NumericVector y)

This function is computing  ditance
covariance<http://en.wikipedia.org/wiki/Distance_correlation#Distance_covariance>.
This function is OK. It give the right answer.
I use this function to compute distance
correltion<http://en.wikipedia.org/wiki/Distance_correlation>
.

//[[Rcpp::export]]
double mydcor(NumericVector x, NumericVector y)
{
    return mydcov(x,y)/sqrt(mydcov(x,x)*mydcov(y,y));
}

Then, I compile the source code using sourceCpp.
And then mydcor(x,y) give a wrong answer.

Here comes the strange part:
In R, I run code as follow

res1 <- mydcov(x,y)/sqrt(mydcov(x,x)*mydcov(y,y))

a <- mydcov(x,y)
b <- mydcov(x,x)
c <- mydcov(y,y)
res2 <- a/sqrt(b*c)

and res2 is different from res1.(res2 is the right answer.)

And I have another test, rewriting the source code for mydcor():
version1:
//[[Rcpp::export]]
double mydcor(NumericVector x, NumericVector y)
{
    double a = mydcov(x,y)
    double b = mydcov(x,x);
    double c = mydcov(y,y);
    return (a/sqrt(b*c));
}

version2:
//[[Rcpp::export]]
double mydcor(NumericVector x, NumericVector y)
{
    double a = mydcov(x,y)
    Rcout<<a<<"\n";
    double b = mydcov(x,x);
    Rcout<<b<<"\n";
    double c = mydcov(y,y);
    Rcout<<c<<"\n"
    return (a/sqrt(b*c));
}
This time, version2 make a right answer.
It's too weird. I havn't meet such situation before.

Happy Lunar New Year (the most important festival in China), and Thanks in
advance.

Best regards
ZhangYet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20140117/275c4432/attachment.html>


More information about the Rcpp-devel mailing list