2017-10-13 126 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