[Rcpp-devel] Getting the exact arithmetic as in R when Rcpp is used?
William Dunlap
wdunlap at tibco.com
Mon Jul 8 17:03:08 CEST 2013
> Is there a way to get the exact arithmetic as in R?
Make your sum quad precision ('long double' in g++).
% cat s.cpp
#include <iostream>
int main(int argc, char *argv[])
{
double dSum(0.0);
long double ldSum(0.0);
for(int i=0 ; i < 10 ; i++) {
dSum += 0.1;
ldSum += 0.1;
}
double dLdSum(ldSum);
std::cout << "diff=" << dSum - dLdSum << "\n";
std::cout << " sizeof (double)=" << sizeof (double) << "\n";
std::cout << " sizeof (long double)=" << sizeof (long double) << "\n";
return 0;
}
% g++ s.cpp
% ./a.out
diff=-1.11022e-16
sizeof (double)=8
sizeof (long double)=16
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: rcpp-devel-bounces at lists.r-forge.r-project.org [mailto:rcpp-devel-
> bounces at lists.r-forge.r-project.org] On Behalf Of Peng Yu
> Sent: Monday, July 08, 2013 4:52 AM
> To: rcpp-devel at lists.r-forge.r-project.org
> Subject: [Rcpp-devel] Getting the exact arithmetic as in R when Rcpp is used?
>
> Hi,
>
> The following shows the arithmetic in C++ is slightly different from
> in R. Is there a way to get the exact arithmetic as in R?
>
> ~/dvcs_src/rexample/Rexample/cran/base/sum$ Rscript main_Rcpp.R
> > library(inline)
> > src='
> + Rcpp::NumericVector vec(vx);
> + double sum = 0;
> + for (int i=0; i<vec.size(); i++) {
> + sum += vec[i];
> + }
> + return Rcpp::wrap(sum);
> + '
> > fun=cxxfunction(
> + signature(vx='numeric')
> + , src
> + , plugin='Rcpp'
> + )
>
> Attaching package: 'Rcpp'
>
> The following object is masked from 'package:inline':
>
> registerPlugin
>
> > vx=rep(.1, 10)
> > options(digits=22)
> > fun(vx)
> [1] 0.9999999999999998889777
> > sum(vx)
> [1] 1
> >
>
> --
> Regards,
> Peng
> _______________________________________________
> 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