fibonacci series, while loop

22 ビュー (過去 30 日間)
BMNX
BMNX 2019 年 10 月 6 日
編集済み: John D'Errico 2019 年 10 月 6 日
Remember the Fibonacci series:
a(k+1)=a(k)+a(k1) k>2, a(0)=1,a(1)=1 (2)
Interestingly the golden ratio can be calculated from the this series:
— Write a script that calculates the golden ratio from the Nth and (N 1)th Fibonacci numbers.
my code look like this but it didnt work. Can someone help me? Thank you!
a(1) = 1;
a(2) = 1;
n=3
while n <= 16 %the value for this can be changed
a(n) = a(n-1)+a(n-2);
ratio = limit(a(n)/a(n-1),n,inf);
n=n+1;
end
  2 件のコメント
darova
darova 2019 年 10 月 6 日
Where did yu get this information?
John D'Errico
John D'Errico 2019 年 10 月 6 日
The limit will indeed approach the golden ratio. This is a well known fact, and pretty easily proven, based on the Binet formula for the Fibonacci sequence.
(sqrt(5) + 1)/2
ans =
1.61803398874989

サインインしてコメントする。

採用された回答

John D'Errico
John D'Errico 2019 年 10 月 6 日
編集済み: John D'Errico 2019 年 10 月 6 日
Well, what is important to me is you have made a credible effort, and gotten close. In fact, you did compute Fibonacci sequence elements.
First, you should have preallocated the vector a, which would make MATLAB more efficient.
What would i change in the code you show?
N = 16; % how far out
a = zeros(1,N); % preallocation
a(1) = 1;
a(2) = 1;
for n = 3:N % a for loop is simpler to write than a while loop
a(n) = a(n-1)+a(n-2);
end
But how about that ratio thing? You cannot use the limit function to compute a limit as you did. Sorry. But the limit is just the ratio of two consecutive numbers from that sequence. So now, you want to see how well those ratios approach the expected limit as N grows larger.
ratio = zeros(1,N-1);
for n = 1:N-1
ratio(n) = a(n)/a(n+1);
end
format long g
ratio'
ans =
1
2
1.5
1.66666666666667
1.6
1.625
1.61538461538462
1.61904761904762
1.61764705882353
1.61818181818182
1.61797752808989
1.61805555555556
1.61802575107296
1.61803713527851
1.61803278688525
What is the expected limit supposed to be? It is approaching that theoretical limit?

その他の回答 (1 件)

David Hill
David Hill 2019 年 10 月 6 日
If you have the symbolic toolbox you can just use the built in fibonacci function.
estGR = fibonacci(n)/fibonacci(n-1);
Otherwise, the code to calculate the nth fibonacci number is not difficult.

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by