Fibonacci number without any loops?
10 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Roger Stafford
on 8 Feb 2015
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 Comments
More Answers (1)
Guillaume
on 8 Feb 2015
Edited: Guillaume
on 8 Feb 2015
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 Comment
John D'Errico
on 11 Feb 2015
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.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!