Rcpp :: abs默认为int而不是double?

问题描述

在RStudio获取以下cpp文件,当我希望获得双精度数时,您会看到Rcpp :: abs返回一个整数。 std :: abs解决了这个问题。我认为我的期望是错误的,但是为什么呢?为什么要在这里返回一个整数(允许,它是一个双精度值,但只能接受整数值)?

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
NumericVector closestIndices(NumericVector x) {
  int fst = 0;
  int snd = 1;
  int n = x.size();
  double diff = abs(x[snd] - x[fst]);
  Rprintf("diff: %f\n",diff);
  double candDiff;
  
  for(int i = 0; i < n - 1; i++){
    for(int j = i + 1; j < n; j++){
      candDiff = abs(x[j] - x[i]);
      // Rprintf("i: %i\tj: %i\tdiff: %.4f\n",i,j,candDiff);
      if( candDiff < diff){
        fst = i;
        snd = j;
        diff = candDiff;
      }
    }
  }
  
  NumericVector output = {double(fst),double(snd)};
  return output;
}

/*** R
x <- c(0.98799517,1.09055728,1.20383713,1.32927166,1.46857509,1.62380423,1.79743107,1.99241551,2.21226576,2.46106916,2.74346924,3.06455219,3.42958354,3.84350238,4.31005838,4.83051356,5.40199462,6.01590035,6.65715769,7.30532785,7.93823621,8.53773241,9.09570538,9.61755743,10.12099196,10.6301818,11.16783243,11.74870531,12.37719092,13.04922392,13.75661322,14.49087793,15.24414627,16.00601247,16.75709565,17.46236358,18.06882072,18.51050094,18.71908344,18.63563523,18.22123225,17.46709279,16.40246292,15.09417699,13.63404124,12.11854915,10.6305417,9.22947285,7.95056,6.80923943,5.80717982,4.93764782,4.1894745,3.54966795,3.00499094,2.54283599,2.1516578,1.82114213,1.54222565,1.30703661,1.10879707,0.94170986,0.80084308,0.68201911,0.58171175,0.49695298,0.42525021,0.3645135,0.31299262,0.26922281,0.2319786,0.20023468,0.17313291,0.14995459,0.1300973,0.11305559,0.09840485,0.08578789,0.07490387,0.06549894,0.05735864)
closestIndices(x)
*/

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)