从R调用C++函数并对其进行集成时出错
Error when calling C++ function from R and integrate it
我想对一个一维函数(用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
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 将公共但非静态的成员函数与ALGLIB集成
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 将IBM Rhapsody模型集成到VS 2019中
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- 将节点 js 代码集成到 cpp 库时出错
- 集成 SFML 和 wxWidget 时出错