Message Boards Message Boards

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

How create function for Fibonacci series?

Posted 10 years ago

I know Mathematica has the default function for Fibonacci Serie but I need do a function that calculate any number that I introduce, for example:

n=2 fib=[n_]... So the result for the Fibonacci Serie it's 1 (1,1,2,3,5,8...)

Please anyone help me to generate this function and please explain why and the stepwise

POSTED BY: Camilo Pacheco
4 Replies

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

Of course, you could also use the built in function (which means that you do not need to define anything new!):

Fibonacci[#] & /@ Range[20]

This is quite a bit faster than defining your own function.

Cheers,

M.

POSTED BY: Marco Thiel
Posted 10 years ago
POSTED BY: Camilo Pacheco
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

Group Abstract Group Abstract