Fibonacci function

爱⌒轻易说出口 提交于 2019-11-28 08:35:55

问题


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

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

Work so far:

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

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

How are we supposed to generate the wanted function?


回答1:


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)
 }

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.

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)
}


来源:https://stackoverflow.com/questions/22629976/fibonacci-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!