从R调用C++函数并对其进行集成时出错

Error when calling C++ function from R and integrate it

本文关键字:集成 出错 调用 C++ 函数      更新时间:2023-10-16

我想对一个一维函数(用C++编写(与R函数integrate进行数值积分。作为一个简短的例子,我用C++编写了函数myfunc

#include <cmath>
#include <Rcpp.h>
using namespace std;
// [[Rcpp::export]]
double myfunc (double x){
double result;
result = exp( -0.5*pow(x,2) + 2*x );
return result;
}

在R中加载myfunc并对其进行积分后,我得到以下错误:

library(Rcpp)
sourceCpp("myfunc.cpp")
integrate(myfunc,lower=0,upper=10)

f(x,…(中的错误:应为单个值:[extent=21]

有人能解释一下这个错误意味着什么,以及我如何解决这个问题吗?

来自help("integrate"):

f必须接受一个输入向量,并在这些点上产生一个函数求值向量。矢量化函数可能有助于将f转换为这种形式。

您已经创建了接受单个值double的函数,因此当integrate()试图向其传递向量时,它会理所当然地抱怨。所以,试试

#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector myfunc(Rcpp::NumericVector x){
return exp(-0.5 * pow(x, 2) + 2 * x);
}
/*** R
integrate(myfunc, lower = 0, upper = 10)
*/

导致

integrate(myfunc, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08

或者,使用从上面的C++代码编译的myfunc()

f <- Vectorize(myfunc)
integrate(f, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08