问题
I was wondering how Rcpp
could be used to perform numerical integration by calling C++ in R. My current setup takes a really long time and is highly error prone.
I think I need something better than default R numerical integration package. Would doing numerical integration in C++ within R solve these problems?
funk <- function(x,b) { 10^b * exp(-x/10) }
lambda <- function(y,k) { exp(-k*y) }
funk1 <- function(y,x,xb,b,k) {
funk(x-xb-y,b) *exp(- integrate(lambda, lower=0, upper = y, k=k)$value) }
funk2 <-function(x,xb,b,k) {
integrate(funk1, lower= 0, upper=x-xb, x=x,xb=xb, b=b,k=k)$value }
funk2_vc <- Vectorize(funk2)
Thanks in advance for help!
回答1:
You'd have a lot easier time using RcppNumerical
with Rcpp
(and yes, it would make it faster).
The code is a port of NumericalIntegration, which combines relevant parts of Quantlib and a few other C++ libraries like LibLBFGS.
Here's a nice tutorial to get you started.
To compute integration of a function, first define a function 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 tutorial and package documentation should be enough to suit your needs, but if you need more help check out the documentation for the C++ library NumericalIntegration
.
来源:https://stackoverflow.com/questions/39449080/how-to-use-rcpp-to-do-numerical-integration-in-c-within-r