我在 R 工作时注意到一件奇怪的事情。
当我有一个使用 for 循环和 while 循环实现的计算从 1 到 N 的平方的简单程序时,行为并不相同。 (在这种情况下我不关心矢量化或应用函数)。
fn1 <- function (N)
{
for(i in 1:N) {
y <- i*i
}
}
AND
fn2 <- function (N)
{
i=1
while(i <= N) {
y <- i*i
i <- i + 1
}
}
结果是:
system.time(fn1(60000))
user system elapsed
2.500 0.012 2.493
There were 50 or more warnings (use warnings() to see the first 50)
Warning messages:
1: In i * i : NAs produced by integer overflow
.
.
.
system.time(fn2(60000))
user system elapsed
0.138 0.000 0.137
现在我们知道 for 循环更快,我的猜测是因为那里的预分配和优化。但为什么会溢出呢?
更新:所以现在尝试另一种使用向量的方法:
fn3 <- function (N)
{
i <- 1:N
y <- i*i
}
system.time(fn3(60000))
user system elapsed
0.008 0.000 0.009
Warning message:
In i * i : NAs produced by integer overflow
那么也许这是一个奇怪的内存问题?我在 OS X 上运行,内存为 4Gb,所有默认设置都在 R 中。这种情况发生在 32 位和 64 位版本中(除了时间更快)。
Alex
Because 1
是数字,但不是整数(即它是浮点数),并且1:6000
是数字和整数。
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 的平方是 36 亿,这不能用有符号的 32 位整数表示,因此会出现溢出错误:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
然而,36 亿很容易用浮点数表示:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
要修复您的for
代码,转换为浮点表示:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)