【发布时间】:2018-05-19 20:50:59
【问题描述】:
为了求解微分方程,我使用 R 中的 Rcpp 包和 C++ 中的 boost 包。我在 C++ 中创建了 eq 函数,它将 R 函数 mod_cpp 转换为“C++ 函数”(见下文)。接下来将 eq 函数作为参数放入Integrate_const 函数中。最后,我可以用 Rcpp 在 R 中编译它,我得到一个名为 my_fun 的 R 函数,它只依赖于向量 vs. 一切正常。
// [[Rcpp::export]]
void my_fun22(Rcpp::NumericVector &x, const double t){
Function f("mod_cpp");
x=f(_["t"]=t,_["x"]=x);
}
Rcpp::NumericVector nvec(130);
void eq(const state_type &x, state_type &dxdt, const double t){
boost_array_to_nvec2(x, nvec);
my_fun22(nvec,t);
nvec_to_boost_array2(nvec, dxdt);
}
Rcpp::NumericMatrix my_fun(const Rcpp::NumericVector vs) {
state_type x = nvec_to_boost_array(vs); // initial conditions
integrate_const(make_dense_output( 1E-4 , 1E-4 , stepper_type () ) ,
eq , x , 0.0 , 120.0 , 1.0 , write_cout);
return data;
}
问题是mod_cpp函数中包含的我模型的所有参数都是固定的。我现在要做的是创建另一个与 my_fun 完成相同工作但取决于模型的某些参数的函数。更准确地说,创建一个名为 my_fun2(vs, theta) 的函数,它依赖于 vs AND theta。我已经尝试过这样做,但正在努力重新定义 my_fun 函数中的 eq 函数,因为它不允许在 R 中的另一个函数中定义函数。我错过了什么吗?
【问题讨论】:
-
我很快就阅读了你的问题,但你应该看看 RcppNumerical 包和“函子”。