c++ - 从 R 调用 C++ 函数并集成它时出错

标签 c++ r rcpp integrate

我想用 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/

相关文章:

c++ - 改进 malloc() 算法的下一步是什么?

c++ - 在 DirectX 9 中使用可扩展数组绘制三角形

c++ - 如何在声明后将 NumericVector 初始化为特定大小?

r - 使用 R 或 RCpp 计算矩阵中有多少行全部为 TRUE 的最快方法是什么?

c++ - 需要帮助使用 C++ 加载简单的文本数据

c++ - 不能覆盖派生类中的静态初始化

r - 如何将向量强制转换为 tibble?

r - 如何将整数转换为R中的分类数据?

r - 通过应用避免循环 - 值得麻烦吗?

r - 如何在 RCpp 中向数据框添加新列?