【问题标题】:Compute the first 10 Fibonacci numbers计算前 10 个斐波那契数
【发布时间】:2017-10-13 15:17:33
【问题描述】:

我需要在 matlab 中编写一个计算代码 the first 10 Fibonacci numbers 但我在这方面遇到了一些麻烦。我想到了使用这里定义的公式:

https://www.math.hmc.edu/funfacts/ffiles/10002.4-5.shtml

到目前为止,我已经得到了这个

n = 0; 
c = (((1+sqrt(5))/2)^n -((1-sqrt(5))/2)^2)/(sqrt(5));
while (n < 10)
disp(c)
n+1;
end

但正如您可能看到的那样,这是非常错误和不完整的。但我不确定还能做什么。教授希望我们编写正确的代码,这意味着我不能使用 fibonacci(n) 之类的东西。任何帮助将不胜感激:)

【问题讨论】:

    标签: matlab fibonacci


    【解决方案1】:

    记住斐波那契数的定义:

    fib(n) = fib(n-1) + fib(n-2);
    

    你的公式对于计算前 10 个来说太过分了。只需将前 2 个设置为常数,然后使用你所知道的计算其他的(使用数组,因为一旦你计算了第三个,你就可以计算第 4 个)。

    我会留下一些伪代码用于计算它的递归,你应该能够将这个想法翻译成 matlab

    let fib = [0,1,-1,-1...]
    function Fibonacci(n){
      if (fib[n] != -1) return fib[n] // If it exists already, we have it!
      // otherwise, we can calculate it
      // make sure to save the result so we can use it later if needed.
      fib[n] = Fibonacci(n-1) + Fibonacci(n-2);
      return fib[n];
    }
    

    【讨论】:

    • 他说他不想使用递归函数
    • 问题没有说明,它说你不能只使用内置函数。
    【解决方案2】:
    fib_series = [0,1];
    i = 3;
    while length(fib_series) < 10
      fib_series(i) = fib_series(i-1) + fib(i-2);
      i = i+1;
    end
    

    【讨论】:

      【解决方案3】:

      似乎斐波那契数列遵循golden ratio,正如在here 中详细讨论的那样。

      这是在MATLAB File-exchange code中使用的,我在这里写,只是它的本质-

      sqrt5 = sqrt(5);
      alpha = (1 + sqrt5)/2;   %// alpha = 1.618... is the golden ratio
      fibs  = round( alpha.^n ./ sqrt5 )
      

      您可以将整数输入n 以获取Fibonacci Series 中的nth 数字,或输入数组1:n 以获得整个系列。

      请注意,此方法仅在 n = 69 之前有效。

      【讨论】:

        猜你喜欢
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        • 2020-04-02
        • 2017-07-22
        相关资源
        最近更新 更多