[Rcpp-devel] Summing over a numeric vector.

Richard Chandler richard.chandlers at gmail.com
Mon Jan 3 17:08:01 CET 2011


You could also use this:


Summing3 <- cxxfunction(signature(x="numeric"), '
   Rcpp::NumericVector Dvec(x);
   double out = sum(Dvec);
   return Rcpp::wrap(out);
   ',plugin="Rcpp")
x <- rnorm(100)
Summing3(x); sum(x)



Richard



On Mon, Jan 3, 2011 at 11:04 AM, Cedric Ginestet <
c.ginestet05 at googlemail.com> wrote:

> Thanks Douglas,
> How stupid of me!
> Cheers,
>
>
> On 03/01/11 16:00, Douglas Bates wrote:
>
>> 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
>>>
>>>
>>>  _______________________________________________
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110103/cbe66aad/attachment-0001.htm>


More information about the Rcpp-devel mailing list