首页 > 解决方案 > 在 R 中使用 Rcpp 的 cppFunction() 时接收输出 0

问题描述

我正在使用 Rcpp 来加速forR 中的双循环。我已经实现了C++代码,如下所示;然而,不管输入的类型是什么——例如任何类型的向量或数字——我输入函数,我最终总是收到 0 作为结果。

我的代码哪里做错了?

#include<Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double likelihood(NumericVector pA, NumericVector pB,
                  NumericVector pA_bin, NumericVector pB_bin,
                  double x_A, double x_B, double t_l)
{
  int nrow = pA.size();
  int ncol = pB.size();
  int nvec = nrow*(nrow-1)/2;
  int kk = 0;
  NumericVector p_l_nu_vec(nvec);
  //define 4 double variables to store coordinates of 4 vertices of each element
  double x1 = 0;
  double x2 = 0;
  double y1 = 0;
  double y2 = 0;
  //define 4 variables to store likelihood function values at 4 vertices
  double f1 = 0;   //point 1, bottom-left, (x1,y1)
  double f2 = 0;   //point 2, bottom-right, (x2,y1)
  double f3 = 0;   //point 3, top-right, (x2,y2)
  double f4 = 0;   //point 4, top-left, (x1,y2)


  for (int j=0;j<ncol;++j){
    for (int i=0;i<nrow;++i){
      if (i>j){
        // trapzoid rule, taking average of 4 vertices of the triangular 
        x1 = pA_bin[i];    //x value of left, point 1,4
        x2 = pA_bin[i+1];  //x value of right, point 2,3
        y1 = pB_bin[j];    //y value of bottom, point 1,2 
        y2 = pB_bin[j+1];  //y value of top, point 3,4
        f1 = pow(1-x1,t_l-x_A)*pow(x1-y1,x_A-x_B)*pow(y1,x_B);
        f2 = pow(1-x2,t_l-x_A)*pow(x2-y1,x_A-x_B)*pow(y1,x_B);
        f3 = pow(1-x2,t_l-x_A)*pow(x2-y2,x_A-x_B)*pow(y2,x_B);
        f4 = pow(1-x1,t_l-x_A)*pow(x1-y2,x_A-x_B)*pow(y2,x_B);
        //take the average of 4 vertices
        p_l_nu_vec[kk] = 1/4*(f1+f2+f3+f4);
        kk = kk+1;
      }
    }
  }

  //return p_l_nu_vec;
  return kk;
}

R中的示例调用:

p_l_nu_vec_trapzoid = likelihood(pA,pB,pA_bin,pB_bin,x_A,x_B,t_l)

预期结果应该输出一些实数,而不是一直为 0。例如,在这种情况下,输出 kk 记录了迭代次数。

标签: c++rrcpp

解决方案


推荐阅读