[Rcpp-devel] Summing over a numeric vector.

Douglas Bates bates at stat.wisc.edu
Mon Jan 3 17:00:06 CET 2011


You forgot to initialize i in both loops.  It should be

for(int i = 0; i < Ne; i++)

On Mon, Jan 3, 2011 at 9:50 AM, Cedric Ginestet
<c.ginestet05 at googlemail.com> wrote:
> 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
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
>


More information about the Rcpp-devel mailing list