在使用R语言时,我注意到一个有趣的事情。当我使用for循环和while循环实现从1到N的平方计算的简单程序时,它们的行为是不同的。(在这种情况下,我不关心向量化或apply函数)。
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
也许这是一个奇怪的内存问题?我正在使用 Mac OS X,有 4GB 的内存和所有 R 的默认设置。这在 32 位和 64 位版本中都会发生(除了时间更快之外)。
Alex