如何使用 Rcpp 在 R 中的 C++ 中进行数值积分

How to use Rcpp to do numerical integration in C++ within R

我想知道如何通过在 R 中调用 C++ 来使用 Rcpp 执行数值积分。我当前的设置需要很长时间并且很容易出错。

我想我需要比默认 R 数值集成包更好的东西。在 R 中用 C++ 进行数值积分会解决这些问题吗?

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)

在此先感谢您的帮助!

RcppNumericalRcpp 结合使用会更轻松(是的,它会更快)。

代码是NumericalIntegration, which combines relevant parts of Quantlib and a few other C++ libraries like LibLBFGS的端口。

这里 a nice tutorial 让你开始。

要计算函数的积分,首先定义一个继承自的函数 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]);
    }
};

教程和包文档应该足以满足您的需要,但如果您需要更多帮助,请查看 C++ 库的文档 NumericalIntegration