I have seen several conversations in Rcpp-devel mailing list asking how to
compute numerical integration or optimization in Rcpp. While R in fact
has the functions Rdqags
, Rdqagi
, nmmin
, vmmin
etc. in its API
to accomplish such tasks, it is not so straightforward to use them with Rcpp.
For my own research projects I need to do a lot of numerical integration,
root finding and optimization, so to make my life a little bit easier, I
just created the RcppNumerical
package that simplifies these procedures. I haven’t submitted RcppNumerical
to CRAN, since the API may change quickly according to my needs or the
feedbacks from other people.
Basically RcppNumerical
includes a number of open source libraries for
numerical computing, so that Rcpp code can link to this package to use
the functions provided by these libraries. Alternatively, RcppNumerical
provides some wrapper functions that have less configuration and fewer
arguments, if you just want to use the default and quickly get the results.
RcppNumerical
depends on Rcpp
(obviously) and RcppEigen
,
- To use
RcppNumerical
withRcpp::sourceCpp()
, add the following two lines
to the C++ source file:
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]
- To use
RcppNumerical
in your package, add the corresponding fields to theDESCRIPTION
file:
Imports: RcppNumerical
LinkingTo: Rcpp, RcppEigen, RcppNumerical
The numerical integration code contained in RcppNumerical
is based
on the NumericalIntegration
library developed by Sreekumar Thaithara Balan,
Mark Sauder, and Matt Beall.
To compute integration of a function, first define a functor inherited from
the Func
class:
class Func
{
public:
virtual double operator()(const double& x) const = 0;
virtual void operator()(double* x, const int n) const
{
for(int i = 0; i n; i++)
x[i] = this->operator()(x[i]);
}
};
The first function evaluates one point at a time, and the second version
overwrites each point in the array by …read more
Source:: r-bloggers.com