[Rcpp-devel] Summing over a numeric vector.
Cedric Ginestet
c.ginestet05 at googlemail.com
Mon Jan 3 16:50:28 CET 2011
Dear Rcpp experts,
I have the following bizarre problem. Although the second summing C++
function seems easier than the former, it does not produce the correct
answer. See the following reproducible codes:
##########################################
Summing1 <- cxxfunction(signature(x="numeric"), '
Rcpp::NumericVector Dvec(x);
int Ne = Dvec.size();
double out =0;
for(int i; i<Ne; i++) out += (1/Dvec[i])/Ne;
return Rcpp::wrap(out);
',plugin="Rcpp")
x <- rnorm(100)
Summing1(x); mean(1/x)
##########################################
gives:
[1] 0.02950222
[1] 0.02950222
##########################################
Summing2 <- cxxfunction(signature(x="numeric"), '
Rcpp::NumericVector Dvec(x);
int Ne = Dvec.size();
double out =0;
for(int i; i<Ne; i++) out += Dvec[i];
return Rcpp::wrap(out);
',plugin="Rcpp")
x <- rnorm(100)
Summing2(x); sum(x)
############################################
gives:
[1] 0
[1] -9.220588
Any help greatly appreciated.
Cheers,
--
Cedric Ginestet
Centre for Neuroimaging Sciences (L3.04)
NIHR Biomedical Research Centre
Institute of Psychiatry, Box P089
Kings College London
De Crespigny Park
London
SE5 8AF
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110103/18bfac4e/attachment.htm>
More information about the Rcpp-devel
mailing list