R: simple multiplication causes integer overflow

穿精又带淫゛_ 提交于 2019-12-03 13:10:51

Hopefully a graphic representation of what is happening....

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

2614 * 1456000 is a numeric because both the operands are actually of class numeric. The overflow occurs because both nrow and length return integer's and hence the result is an integer but the result exceeds the maximum size representable by the integer class (+/-2*10^9). A numeric or double can hold 2e-308 to 2e+308. So to solve your problem, just use as.numeric(length(A)) or as.double(length(A)).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!