使用Rcpp时只用正数计算returns负数
Calculation with only positive numbers returns negative number when using Rcpp
只计算正数return负数。
源码如下
library(Rcpp)
sourceCpp(code = "
#include <Rcpp.h>
//[[Rcpp::export]]
double test4(int n, int m, int i) {
double out = (double)(n * i) / (double)(m + 1);
return out;
}
")
test4(10000,1000000, as.integer(3*10^5))
使用大值作为参数时会出现这种现象。
我想要正确的 return 值。
我该怎么办?
谢谢。
问题是您使用整数计算乘积 n * i
。如果这些很大,则会出现整数溢出,因为 32 位有符号整数可表示的最大数为 2147483647。对于有符号整数,溢出会导致负数。一个简单的解决方法是在乘法之前进行转换:
library(Rcpp)
sourceCpp(code = "
#include <Rcpp.h>
//[[Rcpp::export]]
double test4(int n, int m, int i) {
double out = (double)n * i / (double)(m + 1);
return out;
}
")
test4(10000,1000000, as.integer(3*10^5))
结果:
2999.997
顺便说一句,我不会在这里更改 C 风格的转换,但恕我直言,通常 C++ 风格的转换是首选。
只计算正数return负数。
源码如下
library(Rcpp)
sourceCpp(code = "
#include <Rcpp.h>
//[[Rcpp::export]]
double test4(int n, int m, int i) {
double out = (double)(n * i) / (double)(m + 1);
return out;
}
")
test4(10000,1000000, as.integer(3*10^5))
使用大值作为参数时会出现这种现象。
我想要正确的 return 值。
我该怎么办?
谢谢。
问题是您使用整数计算乘积 n * i
。如果这些很大,则会出现整数溢出,因为 32 位有符号整数可表示的最大数为 2147483647。对于有符号整数,溢出会导致负数。一个简单的解决方法是在乘法之前进行转换:
library(Rcpp)
sourceCpp(code = "
#include <Rcpp.h>
//[[Rcpp::export]]
double test4(int n, int m, int i) {
double out = (double)n * i / (double)(m + 1);
return out;
}
")
test4(10000,1000000, as.integer(3*10^5))
结果:
2999.997
顺便说一句,我不会在这里更改 C 风格的转换,但恕我直言,通常 C++ 风格的转换是首选。