Effacer les filtres
Effacer les filtres

Fibonacci number without any loops?

3 vues (au cours des 30 derniers jours)
Jim Oste
Jim Oste le 8 Fév 2015
Commenté : John D'Errico le 11 Fév 2015
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.

Réponse acceptée

Roger Stafford
Roger Stafford le 8 Fév 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'.)

Plus de réponses (1)

Guillaume
Guillaume le 8 Fév 2015
Modifié(e) : Guillaume le 8 Fév 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 commentaire
John D'Errico
John D'Errico le 11 Fév 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by