我想用 R 函数 integrate
对一维函数(用 C++ 编写)进行数值积分。作为一个简短的例子,我用 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 must accept a vector of inputs and produce a vector of function evaluations at those points. The Vectorize function may be helpful to convert f to this form.
您已经创建了接受单个值的函数,一个 double
,因此当 integrate()
试图将一个 vector 传递给它时,它会报错。所以,试试
#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
关于c++ - 从 R 调用 C++ 函数并集成它时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074011/