2017-10-13 52 views
-2

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

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 

但你很可能会看到,这是非常错误和不完整的。但我不知道该怎么做。教授希望我们写出正确的代码,这意味着我不能使用像斐波那契(n)这样的东西。任何帮助将不胜感激:)

回答

0
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 
0

似乎像fibonacci系列如下golden ratio,正如一些细节here谈论。

这是在这个MATLAB File-exchange code使用,我写在这里,只是它的esssence -

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

可以在Fibonacci Series养活一个整数到nnth数或饲料数组1:n有整个系列。

请注意,此方法仅适用于n = 69

1

记住一个斐波那契数定义为什么:

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

您的公式计算第10位。只要设置第一2为常数大规模矫枉过正,并计算出其他人(使用数组,因为一旦你计算第三你可以用你知道的来计算第四)。

我会留下一些伪码,计算它递归,你应该能够想法在翻译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]; 
} 
+0

他说,他不希望使用递归funtion –

+1

这个问题没有说明,它说你不能只使用内置函数。 – Imme