Question

I am very new to Rcpp, or more specifically RcppEigen, and struggling with how to use pi as a constant in my code. The code runs numerous time in a MCMC algorithm, so any speed improvement would be perfect. Currently, I hand pi over every time I call the function, as in the following code:

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?

My question: How can I use the constant pi within RcppEigen without passing it over at every call of I.cpp?

Was it helpful?

Solution

First off, grep for pi in /usr/share/R/include/ and you find eg

  #define M_PI        3.141592653589793238462643383280    /* pi */

so that you have where R is used, eg here with Rcpp and RcppEigen.

Example:

R> getpi <- cppFunction('double twopi() { return M_PI; } ')
R> getpi()
[1] 3.142
R> print(getpi(), digits=20)
[1] 3.141592653589793116
R> 

I am sure this is also in the math headers. [ Goes checking: Yup, starting in math.h. ] Probably multiple times. Grep'ing through other sources can be fruitful too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top