R:简单乘法导致整数溢出

use*_*417 8 r integer-overflow

在较长的脚本中,我必须将向量A(2614)的长度乘以数据帧B(1456000)的行数.如果我直接这样做,length(A) * nrow(B)我会得到消息,NAs produced by integer overflow虽然当我乘以相同的数字时没有问题:

2614 * 1456000 
[1] 3805984000 
Run Code Online (Sandbox Code Playgroud)

使乘法运算的唯一方法是round(length(A)) * nrow(B)length(A) * round(nrow(B)).但这些数字所生产lengthnrow必须为整数无论如何!此外,我使用函数is.integer的帮助页面上建议的以下函数对此进行了测试...

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x-round(x)) < tol
Run Code Online (Sandbox Code Playgroud)

......当然,他们是整数.那么为什么我需要拐杖"圆"呢?非常令人费解......有人知道背景中发生了什么?

Sim*_*lon 13

希望是正在发生的事情的图形表示....

2614 * 1456000
#[1] 3805984000

##  Integers are actually represented as doubles
class( 2614 * 1456000 )
#[1] "numeric"

#  Force numbers to be integers
2614L * 1456000L
#[1] NA
#Warning message:
#In 2614L * 1456000L : NAs produced by integer overflow

##  And the result is an integer with overflow warning
class( 2614L * 1456000L )
#[1] "integer"
#Warning message:
#In 2614L * 1456000L : NAs produced by integer overflow
Run Code Online (Sandbox Code Playgroud)

2614 * 1456000numeric因为两个操作数实际上都是类numeric.发生溢出,因为这两个nrowlength返回integer的,因此其结果是一个整数,但结果由超过最大尺寸可表示integer类(+/- 2*10 ^ 9).A numericdouble可以持有2e-308 to 2e+308.所以要解决你的问题,只需使用as.numeric(length(A))as.double(length(A)).