在R中使用Rcpp的cppFunction()时接收输出0

时间:2019-02-14 04:11:49

标签: c++ r rcpp

我正在使用Rcpp加快R中的双for循环。我已经实现了 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记录迭代次数。

0 个答案:

没有答案