c++ - 使用提供的 R 函数使用 gsl_function

标签 c++ r rcpp gsl

我目前正在尝试使用 .cpp 文件通过 RcppGSL 使用 GSL 库中的 gsl_function,并使用 sourceCpp() 调用它。这个想法是用同样来自 GSL 的 gsl_integration_qags 进行数值积分。我的 C 代码调用保存到全局环境中的用户定义的 R 函数(我下面的代码中的 SomeRFunction)。代码是:

#include <RcppGSL.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_vector.h>

// [[Rcpp::depends(RcppGSL)]]
// [[Rcpp::export]]
double integfn1(double ub, double lb, double abserr, double Rsq, int pA){ 

  double result, abserror;
  Rcpp::Environment global = Rcpp::Environment::global_env();
  Rcpp::Function f1 = global["SomeRFunction"];

  struct my_f_params { double Rsq; int pA; };
  struct my_f_params params = { Rsq, pA };
  gsl_function F;
  F.function = & f1;
  F.params = &params;
  double lb1 =  lb;
  double ub1 = ub;

  gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);

  gsl_integration_qags (&F, lb1, ub1, 1e-8, 1e-8, 1000, w, &result, &abserror);

  printf ("result          = % .18f\n", result);
  printf ("estimated error = % .18f\n", abserror);

  gsl_integration_workspace_free (w);

  return result;
}

出现以下错误:

"cannot convert 'Rcpp::Function* {aka Rcpp::Function_Impl<Rcpp::PreserveStorage>*}' to 'double (*)(double, void*)' "

问题出在我声明要集成的函数的行中(即“F.function = & f1;”)。

我查找了类似的问题,但找不到任何列出的内容...任何提示将不胜感激!

非常感谢

最佳答案

我创建了一个工作示例(并针对 C 对其计时),您可以在其中将任意用户定义的 R 函数传递给 GSL 函数 QAWF。您也应该能够将其推广到其他 gsl 函数。

请参阅此处示例:https://sites.google.com/site/andrassali/computing/user-supplied-functions-in-rcppgsl

如上所述,竞争的 C 实现要快得多。

关于c++ - 使用提供的 R 函数使用 gsl_function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332432/

相关文章:

c++ - 创建 IloObjective 的正确方法

c++ - 从数组中删除最低输入?

r - 如何更改xyplot中标题的颜色?

c++ - 我不明白 Rcpp 中的这种行为

c++ - Phong 照明模型实际上并没有照亮任何东西

c++ - CMAKE - 调试/交叉构建?

r - left_join 不合并所有值

r - 如何在数据帧计算中用矢量函数替换 R 中的 for 循环?

c++ - 尝试从 R 调用 C++ 函数时出现 fatal error

r - 为什么 Rtools 3.1 在 Windows 上不支持 C++11