我对 非常陌生Rcpp,或者更具体地说RcppEigen,我正在努力解决如何pi在我的代码中用作常量。代码在 MCMC 算法中运行了很多次,因此任何速度改进都是完美的。目前,我每次调用该函数时都会交出 pi,如下代码所示:
require(RcppEigen)
require(inline)
I.Cpp <- "
using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Rcpp::NumericVector;
const Map<MatrixXd> delta(as<Map<MatrixXd> >(delta0));
const Map<VectorXd> d(as<Map<VectorXd> >(DD));
const Rcpp::NumericVector tpi(pie);
double pi = tpi[0];
const MatrixXd I = delta.transpose() * d.asDiagonal() * pi * pi;
return wrap(I);
"
I.cpp <- cxxfunction(signature(delta0 = "matrix", DD = "numeric", pie = "numeric"), I.Cpp, plugin = "RcppEigen")
delta0 <- matrix(rnorm(25), 5)
DD <- rnorm(5)
I.cpp(delta0, DD, pi) # this piece of code gets called multiple times?
Run Code Online (Sandbox Code Playgroud)
我的问题:我如何使用恒定的pi内RcppEigen不超过传递在每一个电话I.cpp?
首先,grep for piin /usr/share/R/include/,你会发现例如
Run Code Online (Sandbox Code Playgroud)#define M_PI 3.141592653589793238462643383280 /* pi */
这样您就可以使用 R 的地方,例如这里使用 Rcpp 和 RcppEigen。
例子:
R> getpi <- cppFunction('double twopi() { return M_PI; } ')
R> getpi()
[1] 3.142
R> print(getpi(), digits=20)
[1] 3.141592653589793116
R>
Run Code Online (Sandbox Code Playgroud)
我相信这也在数学标题中。[检查:是的,从math.h. ] 可能多次。通过其他来源进行搜索也很有成效。