c++ - RStudio 不断与 Rcpp 崩溃
问题描述
我想了解是什么导致该程序崩溃。我在这里、这里和这里看到了至少三个相关的问题,但我还没有找到解决这个问题的明确答案,所以这里有一些示例代码来复制这个问题。
R代码:
library(Rcpp)
Rcpp::sourceCpp("myfunction.cpp")
data1 <- rnorm(2000)
data2 <- rnorm(2000)
mydata <- matrix(cbind(data1, data2), nrow=2000, ncol=2)
values <- log(1:6)
for (i in 1:1000) {
myfunction(values, mydata)
}
C++ 代码:
#include "Rcpp.h"
#include "math.h"
using namespace Rcpp;
// [[Rcpp::export]]
double myfunction(const NumericVector& theta, const NumericMatrix& data) {
double ans = 0;
int theta_size = theta.length();
NumericVector mytheta(theta_size);
int data_size = data.nrow();
NumericMatrix mat(data_size, 2);
for (int i = 0; i < theta_size; i++) {
mytheta(i) = exp(theta(i));
}
if ( true ) { // Flow control
for (int i = 0; i < data_size; i++) {
mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1);
ans = ans + 1;
}
for (int i = 0; i < data_size; i++) {
mat(i, 2) = pow(data(i-1, 2), 2) + mytheta(4)*mat(i-1, 2);
ans = ans + 1;
}
}
Rcout << "Ok!\n";
return ans;
}
至少在我第一次使用时一切正常myfunction()
,但是在 R for 循环中调用时它会崩溃。我重新安装了 R、Rtools 和 RStudio(在 Windows 上),看看安装是否有问题,但我仍然面临同样的问题。
这使得 R 和 C++ 之间的无缝集成不像我最初想象的那样无缝,而且由于我发现我不是唯一一个面临这个问题的人,看起来我们在开始时都犯了一些明显的错误Rcpp(至少在 RStudio 上),但它是什么?
本质上,我想确保我没有在这里遗漏一些完全明显的东西,因为到目前为止我所看到的所有答案似乎都暗示确实如此。
注意:这是我一直在使用 Rcpp 测试的较长功能的缩短版本,原始版本在我调用它的前几次似乎工作正常,但它最终也崩溃了。
更新:删除 rm(),哎呀。
解决方案
for (int i = 0; i < data_size; i++) { mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1); ans = ans + 1; }
时i == 0
,您尝试访问data(-1, 1)
并且事情从那里变成梨形。它在你第一次运行时没有崩溃的事实只是意味着你很幸运(或不走运,因为它诱使你产生一种虚假的自信感)。
推荐阅读
- mysql - SQL比较同一表中的两行并创建新列
- r - 跟踪纵向数据的状态变化和变化日期
- javascript - React Native 多行文本缩进
- c - 告诉 llvm-cov 忽略一个块?
- node.js - Docker 容器关闭并显示日志“SyntaxError: Unexpected token '<'”
- c - 是否可以在 C 常量表达式中进行联合类型双关语?
- android - 当 android 上的 chrome 将桌面更改为移动模式时,window.location.href 不会返回由 history.replacestate 更新的 URL,反之亦然
- python - 烧瓶将变量传递给 url
- npm-install - 如何解决运行 npm install 后出现的错误?
- quarkus - Quarkus 记录事务 ID