Rcpp移动平均线 - 边界误差导致致命错误

问题描述 投票:0回答:1

我使用滚动加权移动平均函数,其代码如下所示。它通过Rcpp用C ++编写。此功能适用于大多数时间系列,没有循环问题或类似的东西。我在下面提供了一系列长度为2的系列,有时会触发致命错误。我找不到错误的原因。

谢谢你的帮助! =)

这是R代码:

# Install packages
sourceCpp("partialMA.cpp")
spencer_weights=c( -3, -6, -5, 3, 21, 46, 67, 0, 67, 46, 21, 3, -5, -6, -3)
spencer_ma <- function(x) roll_mean(x,spencer_weights)

x=c(11.026420323685528,0.25933761651337001)
spencer_ma(x) # works
for(i in 1:1000) spencer_ma(x) # triggers the fatal error 

我在下面包含了我的roll_mean函数的C ++代码:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector roll_mean(const NumericVector& x,
                        const NumericVector& w) {

  int n = x.size();
  int w_size = w.size();
  int size = (w_size - 1) / 2;

  NumericVector res(n);
  int i, ind_x, ind_w;

  double w_sum = Rcpp::sum(w), tmp_wsum, tmp_xwsum, tmp_w;

  // beginning
  for (i = 0; i < size; i++) {
    tmp_xwsum = tmp_wsum = 0;
    for (ind_x = i + size, ind_w = w_size - 1; ind_x >= 0; ind_x--, ind_w--) {
      tmp_w = w[ind_w];
      tmp_wsum += tmp_w;
      tmp_xwsum += x[ind_x] * tmp_w;
    }
    res[i] = tmp_xwsum / tmp_wsum;
  }

  // middle
  int lim2 = n - size;
  for (; i < lim2; i++) {
    tmp_xwsum = 0;
    for (ind_x = i - size, ind_w = 0; ind_w < w_size; ind_x++, ind_w++) {
      tmp_xwsum += x[ind_x] * w[ind_w];
    }
    res[i] = tmp_xwsum / w_sum;
  }

  // end
  for (; i < n; i++) {
    tmp_xwsum = tmp_wsum = 0;
    for (ind_x = i - size, ind_w = 0; ind_x < n; ind_x++, ind_w++) {
      tmp_w = w[ind_w];
      tmp_wsum += tmp_w;
      tmp_xwsum += x[ind_x] * tmp_w;
    }
    res[i] = tmp_xwsum / tmp_wsum;
  }

  return res;
}
c++ r rcpp fatal-error
1个回答
5
投票

A Wild Index Out of Bounds Error Appeared!

您可以通过将元素访问器从[]切换到()来查明问题。后者具有内置边界检查,例如是index0之间的n-1

使用内置检查运行代码可以:

 Error in roll_mean(x, spencer_weights) : 
  Index out of bounds: [index=7; extent=2]. 

因此,使用的索引大大超过了向量的长度。添加trace语句表明它的第一个循环是错误的。

#include <Rcpp.h>
// [[Rcpp::export]]
NumericVector roll_mean(const NumericVector& x,
                        const NumericVector& w) {

  int n = x.size();
  int w_size = w.size();
  int size = (w_size - 1) / 2;

  Rcpp::Rcout << n << ", w_size: " << w_size << ", size: " << size << std::endl;

  NumericVector res(n);
  int i, ind_x, ind_w;

  double w_sum = Rcpp::sum(w), tmp_wsum, tmp_xwsum, tmp_w;

  // beginning
  for (i = 0; i < size; i++) {
    tmp_xwsum = tmp_wsum = 0;

    // Fix this line
    for (ind_x = i + size, ind_w = w_size - 1; ind_x >= 0; ind_x--, ind_w--) { 
      tmp_w = w(ind_w);
      Rcpp::Rcout << "Loop at: " << ind_w << std::endl;
      tmp_wsum += tmp_w;
      tmp_xwsum += x(ind_x) * tmp_w;
    }

    res(i) = tmp_xwsum / tmp_wsum;
  }

  Rcpp::Rcout << "success" << std::endl;
  return res;
}

这就是所有人!

© www.soinside.com 2019 - 2024. All rights reserved.