繁体   English   中英

从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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM