Reputation: 11
I want to numerically integrate a 1-dimensional function (that was written in C++) with the R function integrate
. As a short example, I coded the function myfunc
in C++.
#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;
}
After loading myfunc
in R and integrating it, I obtain the following error:
library(Rcpp)
sourceCpp("myfunc.cpp")
integrate(myfunc,lower=0,upper=10)
Error in f(x, ...) : Expecting a single value: [extent=21].
Can anyone explain what this error means and how I can solve this problem?
Upvotes: 1
Views: 159
Reputation: 16940
From 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.
You have created your function to accept a single value, a double
, so when integrate()
tries to pass it a vector, it rightfully complains. So, try
#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)
*/
Resulting in
integrate(myfunc, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08
Or, using myfunc()
compiled from your C++ code from above,
f <- Vectorize(myfunc)
integrate(f, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08
Upvotes: 4