【问题标题】:increase precision in Rcpp floating-point output提高 Rcpp 浮点输出的精度
【发布时间】:2013-12-24 21:26:08
【问题描述】:

我正在尝试从 Rcpp 函数的双精度输出中打印更多数字,但无法弄清楚如何...我查看了 How do I print a double value with full precision using cout? 和其他地方的通用 C++ 答案,但是我在Rcpp 中看不到如何操作,除非使用printf,我认为这是最后的手段...

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

【问题讨论】:

标签: r rcpp


【解决方案1】:

你总是可以走另一条路:

# 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> 

与此同时,@Manetheran 还向您展示了标准的 iomanip 路线。

当然还有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> 

哦,为了记录,这些也适用于您想要的输入:

R> ben(1)
[1] "1.000000000000000"
R> ben2(1)
1.000000000000000
R> 

【讨论】:

    【解决方案2】:

    查看您的链接答案,您错过了对std::fixed 的呼叫:

    code2 <- '
         double x=1.0;
         Rcpp::Rcout.precision(10);
         Rcpp::Rcout << "(1) " << std::fixed << x << std::endl;
         return Rcpp::wrap(0);
    '
    fun2 <- rcpp(sig=c(v=0),body=code2,includes="#include <iomanip>")
    fun2(1)
    ## (1) 1.0000000000
    ## [1] 0
    

    【讨论】:

    • 值得注意的是,如果你将Rcpp:Rcout.precision 换成std::cout.precision,你会得到奇怪的行为:它只打印出六位数而不是10。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2010-09-27
    相关资源
    最近更新 更多