Rcpp:使用双精度类型的浮点异常



我试着在cpp中写一个简单的函数,可以在rcpp中使用,比如:

#include <Rcpp.h> 
using namespace Rcpp;
// [[Rcpp::export]]
inline static double calc(double a, double b, double c){ 
    return a - b + c;
}
// [[Rcpp::export]]
void other_function() {
    double res = calc(1.00, 0.00, 3.00);        // no error
    NumericVector resV;
    resV[0] = calc(1.00, 0.00, 3.00);   // Floating point exception
    Rcout << res;                       // Floating point exception
}

但每次我试图访问函数calc((的结果时,都会得到一个浮点异常

如果我只获取R文件并从控制台调用函数res((,一切似乎都很好:

source("myscript.R")
calc(1.00,0.00,3.00)
>> 4.00

我已经尝试过的:

  • 将double转换为NumericVector res,并且仅使用res[0]>不工作

  • try float>不工作

  • 直接在other_function中进行计算>相同错误

更新:

每次我尝试在其他函数中调用other_function((时,我都会收到以下消息:

Floating point exception

例如:

void another_function() {
    other_function();       // produce Floating point exception
}

如果我直接在R中调用other_function((,一切都很好!

此外,这个代码(感谢snake_style(对我不起作用:

NumericVector resV = NumericVector::create(progressionC(1.00, 0.00, 3.00));

已解决

我通过简单地重新安装Rcpp包解决了问题。我不知道我为什么会犯这个错误。。。不管怎样,现在它起作用了。

这样尝试:

NumericVector resV = NumericVector::create(calc(1.00, 0.00, 3.00));

不是答案,但我想存储我在复制此问题时失败的尝试。我在带有gcc 6.3的Debian稳定版上使用R 3.5.1。我使用了以下代码:

#include <Rcpp.h> 
using namespace Rcpp;
// [[Rcpp::export]]
inline static double calc(double a, double b, double c){ 
  return a - b + c;
}
// [[Rcpp::export]]
void other_function() {
  double res = calc(1.00, 0.00, 3.00);        // no error
  NumericVector resV;
  resV[0] = calc(1.00, 0.00, 3.00);   // Floating point exception
  NumericVector resV1(1);
  resV1[0] = calc(1.00, 0.00, 3.00);   // Floating point exception
  NumericVector resV2 = NumericVector::create(calc(1.00, 0.00, 3.00));
  Rcout << res << "/" << resV << "/" << resV1 << "/" << resV2;                       // Floating point exception
}

// [[Rcpp::export]]
void another_function() {
  other_function();       // produce Floating point exception
}
/*** R
calc(1.00, 0.00, 3.00)
other_function()
another_function()
*/

调用Rcpp::sourceCpp()编译此代码并产生以下输出:

> calc(1.00, 0.00, 3.00)
[1] 4
> other_function()
4//4/4
> another_function()
4//4/4
  • 没有运行时错误
  • 在原始代码中,calc的结果没有赋值(resV不输出任何结果(
  • 如果指定了向量的大小,或者如果calc与静态create方法一起使用,则赋值有效,如@sake_style所建议的

最新更新