R 中是否使用了递归函数? [英] Are recursive functions used in R?

查看:65
本文介绍了R 中是否使用了递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

演示递归的规范函数是 factorial() 函数.我自己尝试了一个简单的实现并想出了这个:

The canonical function to demonstrate recursion is the factorial() function. I tried a simple implementation of it myself and came up with this:

factorial <- function(x){

if(x==1)
    return( 1)
else
    return(x*factorial(x-1))

}

从我对该主题的调查来看,似乎存在一些关于使用递归还是简单迭代更好的争论.我想看看 R 如何实现它并在 gregmisc 包中找到了一个 factorial() 函数.我想我会找到类似我的实现或定期迭代的东西.我发现了什么:

From my survey of the topic, there seems to be some debate about whether it's better to use recursion or simple iteration. I wanted to see how R implements it and found a factorial() function in the gregmisc package. I thought I'd find something like my implementation or instead a regular iteration. What I found this:

> factorial
function (x) 
gamma(x + 1)
<environment: namespace:base>

因此,我对 R 是否更喜欢递归或迭代的问题的答案是都不是".至少在这个实现中.是否有充分的理由在 R 中避免使用递归函数?

So the answer to my question of whether R prefers recursion or iteration is "neither". At least in this implementation. Are recursive functions avoided in R for good reason?

更新:

gregmisc 版本:

gregmisc version:

>ptm <- proc.time()
> factorial(144)
[1] 5.550294e+249
> proc.time() - ptm
   user  system elapsed 
  0.001   0.000   0.001 

我的版本:

> factorial(144)
[1] 5.550294e+249
> proc.time() - ptm
  user  system elapsed 
  0.002   0.001   0.006 

推荐答案

对于整数阶乘的计算,递归实现更慢,更复杂.在生产代码中总是使用迭代.

For calculation of integer factorial, the recursive implementation is slower and more complex. Invariably, iteration is used in production code.

您所指的 factorial 函数在基础包中.它对实数值而不是整数进行运算,因此是该实现.其文档说明:

The factorial function you refer to is in the base package. It operates on real values rather than integers, hence that implementation. Its documentation states:

factorial(x) (x! 表示非负整数 x) 定义为 gamma(x+1)

factorial(x) (x! for non-negative integer x) is defined to be gamma(x+1)

一个更有趣的例子是实现斐波那契数列的代码,当用朴素的递归实现时,这会非常浪费.递归方法可以通过记忆来提高效率,但如果性能受到威胁,简单的迭代总是首选.

A more interesting example is code to implement the Fibonnaci series which is extraordinarily wasteful when implemented with a naive recursion. The recursive approach can be made efficient through memoization but simple iteration is always to be preferred if performance is at stake.

另一种以递归方式自然表达的常见算法是快速排序.这可以像所有算法一样在没有递归的情况下实现,但这样做非常复杂.使用非递归快速排序几乎没有什么好处,因此使用朴素的递归实现是很常见的.

Another common algorithm that is expressed naturally in a recursive way is Quicksort. This can, like all algorithms be implemented without recursion, but is quite complex to do so. There is little benefit in using a non-recursive Quicksort and so it's common to use the naive recursive implementation.

递归是一个很好的实现选择:

Recursion is a good implementation choice:

  • 如果性能没有受到影响,并且
  • 如果递归实现更自然(因此更容易验证和维护).

这篇关于R 中是否使用了递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆