Fibonacci function

此生再无相见时 提交于 2019-11-29 14:36:08

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