<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
  </head>
  <body text="#000000" bgcolor="#ffffff">
    Dear Rcpp experts, <br>
    <br>
    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:<br>
    <br>
    ##########################################<br>
    Summing1 &lt;- cxxfunction(signature(x="numeric"), '<br>
    &nbsp;&nbsp;&nbsp; Rcpp::NumericVector Dvec(x);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>
    &nbsp;&nbsp;&nbsp; int Ne = Dvec.size();&nbsp;&nbsp;&nbsp;&nbsp; <br>
    &nbsp;&nbsp;&nbsp; double out =0; <br>
    &nbsp;&nbsp;&nbsp; for(int i; i&lt;Ne; i++) out += (1/Dvec[i])/Ne;&nbsp; <br>
    &nbsp;&nbsp;&nbsp; return Rcpp::wrap(out);<br>
    ',plugin="Rcpp")<br>
    x &lt;- rnorm(100)<br>
    Summing1(x); mean(1/x)<br>
    ##########################################<br>
    gives:<br>
    [1] 0.02950222<br>
    [1] 0.02950222<br>
    <br>
    ##########################################<br>
    Summing2 &lt;- cxxfunction(signature(x="numeric"), '<br>
    &nbsp;&nbsp;&nbsp; Rcpp::NumericVector Dvec(x);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>
    &nbsp;&nbsp;&nbsp; int Ne = Dvec.size();&nbsp;&nbsp;&nbsp;&nbsp; <br>
    &nbsp;&nbsp;&nbsp; double out =0; <br>
    &nbsp;&nbsp;&nbsp; for(int i; i&lt;Ne; i++) out += Dvec[i];&nbsp; <br>
    &nbsp;&nbsp;&nbsp; return Rcpp::wrap(out);<br>
    ',plugin="Rcpp")<br>
    x &lt;- rnorm(100)<br>
    Summing2(x); sum(x)<br>
    ############################################<br>
    gives:<br>
    [1] 0<br>
    [1] -9.220588<br>
    <br>
    Any help greatly appreciated.<br>
    Cheers,<br>
    <br>
    <br>
    <div class="moz-signature">-- <br>
      <div class="moz-signature"><font face="Times" size="3">
          Cedric Ginestet <br>
          Centre for Neuroimaging Sciences (L3.04) <br>
          NIHR Biomedical Research Centre <br>
          Institute of Psychiatry, Box P089 <br>
          Kings College London <br>
          De Crespigny Park<br>
          London <br>
          SE5 8AF <a class="moz-txt-link-abbreviated"
            href="mailto:cedric.ginestet@kcl.ac.uk"></a><br>
        </font>
      </div>
    </div>
  </body>
</html>