【问题标题】:R: simple multiplication causes integer overflowR:简单的乘法导致整数溢出
【发布时间】:2013-07-15 09:24:44
【问题描述】:

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

2614 * 1456000 
[1] 3805984000 

使乘法起作用的唯一方法是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

...当然,它们是整数。那么为什么我需要拐杖“圆”在这里?非常令人费解...有人知道背景中发生了什么?

【问题讨论】:

  • 2614 * 1456000not 整数...&gt; class(1456000) [1] "numeric" &gt; class(1456000L) [1] "integer"
  • @Michele 谢谢,因为这个评论,我更新了我的答案。

标签: r integer-overflow


【解决方案1】:

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

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 * 1456000numeric,因为这两个操作数实际上都属于 numeric 类。发生溢出是因为nrowlength 都返回integer,因此结果是一个整数,但结果超过了integer 类可表示的最大大小(+/-2*10^9)。 numericdouble 可以容纳 2e-308 to 2e+308。所以要解决您的问题,只需使用as.numeric(length(A))as.double(length(A))

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多