Fibonacci number without any loops?
10 ビュー (過去 30 日間)
古いコメントを表示
My problem is to use the fprintf command to print out the first N Fibonacci numbers in a two-column table under heading N and F_N. And for the case N >= 50, print out the last 10 Fibonacci numbers F_i for i = N - 9 in a similar two-column table.
0 件のコメント
採用された回答
Roger Stafford
2015 年 2 月 8 日
Here is a formula (not using loops) for the Fibonacci numbers ranging from n = n1 to n = n2:
L1 = (1+sqrt(5))/2;
L2 = (1-sqrt(5))/2;
A = 1/sqrt(5);
n = (n1:n2)';
F(n) = round(A*(L1.^n-L2.^n));
(The 'round' call is to correct for round-off errors. The formula is valid up to about n = 70 at which point round-off errors become too large to correct with 'round'.)
0 件のコメント
その他の回答 (1 件)
Guillaume
2015 年 2 月 8 日
編集済み: Guillaume
2015 年 2 月 8 日
Loren had a blog entry on various methods to calculate Fibonacci numbers. filter is actually very good for this.
Fib = @(n) filter(1, [1 -1 -1], [1 zeros(1, n-1)]);
1 件のコメント
John D'Errico
2015 年 2 月 11 日
I would NOT say it was very good. Filter has good and bad aspects to it for Fibonacci numbers. Filter will probably fail around the same time any other scheme fails in terms of double precision arithmetic.
Filter is nice if you wish to compute all of the Fibonacci numbers that do not exceed a certain limit. As Roger points out, that limit is somewhere around n = 70, although I've not verified his statement.
However, if you just wish to compute certain specific Fibonacci numbers, filter does some extra work, because it computes all of them up to that point. There are other schemes that do not need to compute all such numbers. Roger shows one. I describe in great detail in one of my FEX submissions just some of the many various schemes one might use.
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!