Group Abstract Group Abstract

Message Boards Message Boards

1
|
14.3K Views
|
4 Replies
|
11 Total Likes
View groups...
Share
Share this post:

How create function for Fibonacci series?

Posted 11 years ago
POSTED BY: Camilo Pacheco
4 Replies
POSTED BY: Henrik Schachner
Posted 11 years ago

Thank you very mucho Henrik and Marco.

Henrik I prefer the first option, because in the class we're learning recursion from the functions, for example to generate the Euclidean algorithm:

Euclides[n_, 0] := n;

Euclides[n, r] := Euclides[r, Mod[n, r]];

In the exercise we have the plant case and the other cases that will probably generate, but Henrik in your recursion I don't understand the part of: recFib[n_] := recFib[n] = recFib[n - 1] + recFib[n - 2]

Can you explain me more deep please. If I do recFib[4] the function do: [4-1]+[4-2] or how? I really learn more about recursion functions. Thank you.

POSTED BY: Camilo Pacheco
POSTED BY: Marco Thiel

Hi Camilo,

programmig the Fibonacci Serie is a very standard exercise - and that is probably the origin of your question. There are basically two ways to do it:

One can use the recursion directly:

Clear[recFib];
recFib[n_] := recFib[n] = recFib[n - 1] + recFib[n - 2]
recFib[0] = 0; recFib[1] = 1;

This is elegant but in no way effective! (The double definition "recFib[n_] := recFib[n] =..." is a nice trick to give memory to a function, see "Functions That Remember Values They Have Found" in the documentation.)

A better way is implementing the general formula:

fib[n_] := With[{goldenRatio = (Sqrt[5] + 1)/2}, 
  Simplify[1/Sqrt[5] (goldenRatio^n - (1 - goldenRatio)^n)]]

(Yes, I know, there is a constant "GoldenRatio" predefined, but when using that the simplification to integers does not work ... An idea anybody?) From this formula it is obvious that the term "(1 - goldenRatio)^n" vanishes for large n (its absolute value is smaller than 1). Consequently the expression

fibApprox[x_]:= GoldenRatio^x/Sqrt[5.]

serves as a good approximation - and one can see that the growth is exponential (as it should be with rabbits ...)

Ciao Henrik

POSTED BY: Henrik Schachner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard