Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increase precision in Rcpp floating-point output

Tags:

r

rcpp

I'm trying to print more digits in double-precision output from an Rcpp function, but can't figure out how ... I've looked at How do I print a double value with full precision using cout? and elsewhere for the generic C++ answer, but I can't see how to do it in Rcpp, except by using printf, which I take to be a last resort ...

require(inline)
code <- '
    double x=1.0;
    std::cout.precision(10); // compiles but does nothing
    Rcpp::Rcout.precision(10); // compiles but does nothing
    printf("(1) %1.10lf\\n",x);  // works but bad practice
    Rcpp::Rcout << "(2) " << x << std::endl;
    Rcpp::Rcout << "(3) " << std::setprecision(10) << x << std::endl;
    return Rcpp::wrap(0);
'
fun <- rcpp(sig=c(v=0),body=code,includes="#include <iomanip>")
fun(1)
## (1) 1.0000000000
## (2) 1
## (3) 1
## [1] 0
like image 515
Ben Bolker Avatar asked Dec 24 '13 21:12

Ben Bolker


1 Answers

You can always go another route:

# next line is really one line wrapped here
R> cppFunction('std::string ben(double val) { char buf[32]; \
                                              snprintf(buf, 31, "%15.15f", val);\
                                              return std::string(buf); }')
R> ben(1/3)
[1] "0.333333333333333"
R> ben(1e6/3)
[1] "333333.333333333313931"
R> ben(1e12/3)
[1] "333333333333.333312988281250"
R> 

And in the meantime @Manetheran also showed you the standard iomanip route.

And there is of course also Rprintf().

## the double backslash is needed only for cppFunction
R> cppFunction('void ben2(double val) { Rprintf("%15.15f\\n", val); }')
R> ben2(1e12/3)
333333333333.333312988281250
R> ben2(1e6/3)
333333.333333333313931
R> 

Oh, and for the record, these also work with your desired input of one:

R> ben(1)
[1] "1.000000000000000"
R> ben2(1)
1.000000000000000
R> 
like image 122
Dirk Eddelbuettel Avatar answered Sep 24 '22 23:09

Dirk Eddelbuettel