本文介绍了R中的For循环vs while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我注意到一个奇怪的事情,而工作在R. 当我有一个简单的程序,计算广场从1到N实现使用for循环和while循环的行为是不一样的。 (我不关心在这种情况下的矢量化或者应用函数)。 $ $ $ $ $ $ $ $ $ $ $ $ $ b { for(i in 1:N){y< - i * i } } $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (i 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 y } 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 (1)中的(i)中的函数(N) {){y } } 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 }}ANDfn2 <- 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.493There 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.137Now 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.009Warning message:In i * i : NAs produced by integer overflowSo 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] NAWarning message:In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow3.6 billion is easily representable in floating point, however:> as.single(60000)*as.single(60000)[1] 3.6e+09To 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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 17:03