Fibonacci number without any loops?

10 visualizaciones (últimos 30 días)
Jim Oste
Jim Oste el 8 de Feb. de 2015
Comentada: John D'Errico el 11 de Feb. de 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.

Respuesta aceptada

Roger Stafford
Roger Stafford el 8 de Feb. de 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'.)

Más respuestas (1)

Guillaume
Guillaume el 8 de Feb. de 2015
Editada: Guillaume el 8 de Feb. de 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 comentario
John D'Errico
John D'Errico el 11 de Feb. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by