斐波那契函数 [英] Fibonacci function

查看:86
本文介绍了斐波那契函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们被赋予了一项任务,但我们无法弄清:

We have been given a task, which we just can't figure out:

编写一个R函数,该函数将生成一个包含第一个n的向量 斐波那契数列的术语.步骤如下: (a)创建向量以将结果存储在其中. (b)初始化前两个元素. (c)以i从3到n运行一个循环,填充第i个元素

Write an R function which will generate a vector containing the first n terms of the Fibonacci sequence. The steps in this are as follows: (a) Create the vector to store the result in. (b) Initialize the first two elements. (c) Run a loop with i running from 3 to n, filling in the i-th element

到目前为止的工作:

vast=function(n){
 vast=vector()
 vast[1]=1
 vast[2]=1
 for(i in 3){vast[i]=vast[i-1]+vast[i-2]}
 }

我们最终遇到的错误是:'closure'类型的对象不是可子集的??

All we end up is with the error: object of type 'closure' is not subsettable ??

我们应该如何生成所需的函数?

How are we supposed to generate the wanted function?

推荐答案

我的投票采用@bdecaf建议的封闭形式(因为这会使您的老师烦恼):

My vote's on closed form as @bdecaf suggested (because it would annoy your teacher):

vast = function(n) round(((5 + sqrt(5)) / 10) * (( 1 + sqrt(5)) / 2) ** (1:n - 1))

但是您可以通过两个小的更改来修复已经拥有的代码:

But you can fix the code you already have with two minor changes:

vast=function(n){
 vast=vector()
 vast[1]=1
 vast[2]=1
 for(i in 3:n){vast[i]=vast[i-1]+vast[i-2]}
 return(vast)
 }

我仍然会遵循已经给出的一些建议-尤其是对向量和函数使用不同的名称,但事实是,有许多不同的方法可以实现目标.一方面,在这种情况下,实际上根本不需要初始化一个空向量,因为我们可以像已经在做的那样在R中使用for循环来扩展向量.例如,您可以执行以下操作:

I would still follow some of the suggestions already given--especially using different names for your vector and your function, but the truth is there are lots of different ways to accomplish your goal. For one thing, it really isn't necessary to initialize an empty vector at all in this instance, since we can use for loops in R to expand the vector as you were already doing. You could do the following, for instance:

vast=function(n){
  x = c(1,1)
  for(i in 3:n) x[i] = x[i-1] + x[i-2]
  return(x)
}

当然,我们都有很多要学习的编程知识,但这就是我们在这里的原因.我们都在某个时候得到某人的帮助,并且在我们也帮助别人改善的同时,我们也都在进步.

Of course, we all have things to learn about programming, but that's why we're here. We all got help from someone at some point and we all get better as we help others to improve as well.

更新:正如@Carl Witthoft指出的那样,最好的方法是在知道矢量大小的情况下将其初始化为适当的大小,以节省时间和空间,因此另一种实现此目的的方法任务应该是:

UPDATE: As @Carl Witthoft points out, it is a best practice to initialize the vector to the appropriate size when that size is known in order save time and space, so another way to accomplish this task would be:

vast=function(n) {
  x = numeric(n)
  x[1:2] = c(1,1)
  for(i in 3:n) x[i] = x[i-1] + x[i-2]
  return(x)
}

这篇关于斐波那契函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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