【问题标题】:R: recursive too slow [duplicate]R:递归太慢[重复]
【发布时间】:2016-01-31 21:08:24
【问题描述】:

我有R运行功能:

f <- function (n) {
if ( n == 1) return (0)
if ( n == 2) return (1)
else return ( f(n-1) + f(n-2))
}

f(50) 需要很长时间来计算。 f(35) 大约需要 30 秒。有没有办法让它在 R 中更快?

编辑。感谢帮助!我使用了它,它立即给了我 f(50)。

> f <- local({
+ memo <- c(1, 1, rep(NA,100))
+ f <- function(x) {
+ if(x == 1) return(0)
+ if(x == 2) return(1)
+ if(x > length(memo))
+ stop("’x’ too big for implementation")
+ if(!is.na(memo[x])) return(memo[x])
+ ans <- f(x-1) + f(x-2)
+ memo[x] <<- ans
+ ans
+ }
+ })

【问题讨论】:

标签: r performance recursion sequence


【解决方案1】:

这是一个递归函数的注释问题,可以通过tail-recursion 解决。不幸的是,似乎R does not support tail call optimization。幸运的是,您始终可以使用迭代解决方案,因为它不必分配堆栈帧,因此应该相当快:

fIter <- function(n) {
  if ( n < 2 )
    n
  else {
    f <- c(0, 1)
    for (i in 2:n) {
      t <- f[2]
      f[2] <- sum(f)
      f[1] <- t
    }
    f[2]
  }
}
fIter(100)'

此程序在 ideone 上运行约 0.45 秒。个人不了解R,程序来源:http://rosettacode.org/wiki/Fibonacci_numbers#R

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多