在linux上由整数溢出+ R生成的NA

web*_*ver 4 r

我在基于UNIX的系统上运行R脚本,该脚本包含大数字的乘法,因此NAs按整数溢出的结果,但是当我在Windows上运行相同的脚本时,不会出现此问题.

但我应该让脚本整夜在桌面上运行(这是Unix).

这个问题有什么解决方案吗?

谢谢

for(ol in seq(1,nrow(yi),by=25))
    {
    for(oh in seq(1,nrow(yi),by=25))
 {

        A=(N*(ol^2)) + ((N*(N+1)*(2*N+1))/6) -(2*ol*((N*N+1)/2)) + (2*N*ol*(N-oh+1)) + ((N-oh+1)*N^2) + (2*N*(oh-N-1)*(oh+N))


}
}

    with :
N=16569 = nrow(yi)
Run Code Online (Sandbox Code Playgroud)

但第一轮没有在unix上计算.

NPE*_*NPE 6

您可以将整数转换为浮点数以便使用浮点数学进行计算吗?

例如:

> x=as.integer(1000000)
> x*x
[1] NA
Warning message:
In x * x : NAs produced by integer overflow
> x=as.numeric(1000000)
> x*x
[1] 1e+12
Run Code Online (Sandbox Code Playgroud)

顺便说一句,尚不清楚为什么警告会出现在一个环境中而不是另一个环境中。我最初认为 R 的 32 位和 64 位版本可能分别使用 32 位和 64 位整数,但似乎并非如此。就警告的显示方式而言,您的两个环境的配置是否相同?


Ben*_*ker 5

正如其他答案所指出的那样,到目前为止,你的结果还有一些不可复制/奇怪的东西.然而,如果你真的必须对大整数进行精确计算,你可能需要R和其他系统之间的接口.

你的一些选择是:

  • gmp包(请参阅本页面和向下滚动至R
  • googlecode上bc计算器的接口
  • R维基上有一个高精度算术页面,它将接口与Yacas,bc和MPFR/GMP进行比较
  • 包中的PARI/GP包有一个有限的接口elliptical,但这可能(很多)不如前三个选择那么有用

    大多数Unix或Cygwin系统都应该已经安装了bc.GMP和Yacas易于在现代Linux系统上安装......

这是一个扩展示例,其函数可以在数字,整数或bigz计算中进行选择.

f1 <- function(ol=1L,oh=1L,N=16569L,type=c("num","int","bigz")) {
  type <- match.arg(type)
  ## convert all values to appropriate type
  if (type=="int") {
    ol <- as.integer(ol)
    oh <- as.integer(oh)
    N <- as.integer(N)
    one <- 1L
    two <- 2L
    six <- 6L
    cc <- as.integer
  } else if (type=="bigz") {
    one <- as.bigz(1)
    two <- as.bigz(2)
    six <- as.bigz(6)
    N <- as.bigz(N)
    ol <- as.bigz(ol)
    oh <- as.bigz(oh)
    cc <- as.bigz
  } else {
    one <- 1
    two <- 2
    six <- 6
    N <- as.numeric(N)
    oh <- as.numeric(oh)
    ol <- as.numeric(ol)
    cc <- as.numeric
  }
  ## if using bigz mode, the ratio needs to be converted back to bigz;
  ## defining cc() as above seemed to be the most transparent way to do it
  N*ol^two + cc(N*(N+one)*(two*N+one)/six) -
    ol*(N*N+one) + two*N*ol*(N-oh+one) +
      (N-oh+one)*N^two + two*N*(oh-N-one)*(oh+N)
}
Run Code Online (Sandbox Code Playgroud)

我删除了很多不必要的括号,这实际上让人很难看到发生了什么.确实,对于(1,1)情况,最终结果不大于.Machine$integer.max但是一些中间步骤是......(对于(1,1)情况,这实际上减少到$$ - 1/6*(N + 2)*(4*N ^ 2-5*N + 3)$$ ...)

f1()  ##  -3.032615e+12
f1() > .Machine$integer.max  ## FALSE
N <- 16569L
N*(N+1)*(2*N+1) > .Machine$integer.max   ## TRUE
N*(N+1L)*(2L*N+1L)  ## integer overflow (NA)
f1(type="int")      ## integer overflow
f1(type="bigz")     ##  "-3032615078557"
print(f1(),digits=20)  ##  -3032615078557: no actual loss of precision in this case
Run Code Online (Sandbox Code Playgroud)

PS:你(N*N+1)的等式中有一个术语.真的应该是N*(N+1),还是你真的是这个意思N^2+1