C++ 调用C+时出错+;从R函数开始并将其集成

C++ 调用C+时出错+;从R函数开始并将其集成,c++,r,rcpp,integrate,C++,R,Rcpp,Integrate,我想将一维函数(用C++编写)与R函数进行数值积分integrate。作为一个简短的例子,我在C++中对函数 MyFunc < /C>进行了编码。p> #include <cmath> #include <Rcpp.h> using namespace std; // [[Rcpp::export]] double myfunc (double x){ double result; result

我想将一维函数(用C++编写)与R函数进行数值积分
integrate
。作为一个简短的例子,我在C++中对函数<代码> MyFunc < /C>进行了编码。p>
    #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;
    }
f(x,…)中出错:应为单个值:[范围=21]

有人能解释一下这个错误的含义以及我如何解决这个问题吗?

来自
帮助(“集成”)

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)
*/
帮助(“集成”)

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)
*/

阅读本手册所能达到的惊人效果:)祝贺您将
RcppDist
安装到CRAN上!谢谢@DirkEddelbuettel!一两天内,您可能会收到在
RcppDist
上发布Rcpp图库帖子的请求。阅读手册可以实现的惊人功能:)祝贺您将
RcppDist
安装到CRAN上!谢谢@DirkEddelbuettel!一两天后,您将收到在
RcppDist
上发布Rcpp图库帖子的请求。
integrate(myfunc, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08
f <- Vectorize(myfunc)
integrate(f, lower = 0, upper = 10)
# 18.10025 with absolute error < 5.1e-08