R中的For循环vs while循环 [英] For-loop vs while loop in R
问题描述
当我有一个简单的程序,计算广场从1到N实现使用for循环和while循环的行为是不一样的。 (我不关心在这种情况下的矢量化或者应用函数)。
$ $ $ $ $ $ $ $ $ $ $ $ $ b {
for(i in 1:N){
y< - i * i
}
}
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (i <= N){
y< -i * i
i< i + 1
} $ b $时,$ b {
i = 1
b)
结果是:
system.time(fn1(60000))
用户系统已用
2.500 0.012 2.493
有50个或更多警告(使用警告()第一个50)
警告信息:
1:在i * i:由整数溢出产生的
。
。
。
system.time(fn2(60000))
用户系统已用
0.138 0.000 0.137
现在我们知道for循环更快,我的猜测是因为预分配和优化。但为什么会溢出?
更新:所以现在尝试另外一种方法:
fn3 < - 函数(N)
{
i < - 1:N
y < - i * i
}
system.time(fn3(60000))
用户系统已经过
0.008 0.000 0.009
警告信息
在i * i中:由整数溢出产生的NA
所以,它可能是一个时髦的记忆问题?我在OS X上运行着4Gb的内存和R中的所有默认设置。这发生在32位和64位版本(除了时间更快)。
Alex
因为 1
是数字,但不是整数浮点数), 1:6000
是数字和整数。
> print(class(1))
[1]numeric
> print(class(1:60000))
[1]integer
60000 squared是36亿,这是不能表示32位的整数,因此你得到一个溢出错误:
> as.integer(60000)* as.integer(60000)
[1] NA
警告信息:
as.integer(60000)* as.integer(60000)整数溢出
然而,36亿美元很容易表现在浮点数中:
> as.ingle(60000)* as.single(60000)
[1] 3.6e + 09
<$ c (1)中的(i)中的函数(N)
{
){
y < - i * i
}
}
I have noticed a curious thing whilst working in R. When I have a simple program that computes squares from 1 to N implemented using for-loop and while-loop the behaviour is not the same. (I don't care about vectorisation in this case or apply functions).
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
}
}
The results are:
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
Now we know that for-loop is faster, my guess is because of pre allocation and optimisations there. But why does it overflow?
UPDATE: So now trying another way with vectors:
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
So Perhaps its a funky memory issue? I am running on OS X with 4Gb of memory and all default settings in R. This happens in 32- and 64-bit versions (except that times are faster).
Alex
Because 1
is numeric, but not integer (i.e. it's a floating point number), and 1:6000
is numeric and integer.
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
3.6 billion is easily representable in floating point, however:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
To fix your for
code, convert to a floating point representation:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
这篇关于R中的For循环vs while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!