Fibonacci Sequence Generator

I'm trying to write a function in Workbench which will generate a Fibonacci sequence starting with F0 = 0 and F1 = 1. So far I have this written

fibonacciSequence[n_] :=
Module[{fPrev = 0, fNext = 1, i = 0},
While[i++ < n, {fPrev, fNext} = {fNext, fPrev + fNext}];
fNext]

How do I modify the function to make it print out a list like the one below when fibonacciSequence is called?

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

Sorry, but I am very new to Mathematica and my professor didn't give us much instructions or examples of similar functions.

• you may try Table[Fibonacci[n], {n, 15}] see the doc reference.wolfram.com/mathematica/ref/Fibonacci.html – s.s.o Sep 3 '13 at 14:38
• @s.s.o I'd use Array[Fibonacci, 15] or Fibonacci @ Range @ 15 myself. – Mr.Wizard Sep 3 '13 at 14:47
• @Mr.Wizard Anytime educative suggestions are welcome. Time to practice alternative coding :) Thank you. – s.s.o Sep 4 '13 at 6:49

I'm really surprised if this question isn't a duplicate, but since I failed to find one that asked about the Fibonacci sequence rather than someone using it as an example, I'll answer.

The most natural approach, besides using the built-in Fibonacci function, recursion:

f = 0; f = 1;
f[n_] := f[n] = f[n - 1] + f[n - 2]  (* note memoization *)

Array[f, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Better performing may be Nest and NestList:

fibonacciList[n_] := Module[{x = 0}, NestList[x + (x = #) &, 1, n - 1]]

fibonacciList
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Another useful way uses LinearRecurrence:

LinearRecurrence[{1, 1}, {1, 1}, 10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

Hopefully these examples inspire you.

I now note that you request the sequence starting from zero. Most of these are easy to adapt or modify. The first one is simply:

Array[f, 10, 0]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

For the second you may instead write:

fibonacciList2[n_] := Module[{x = 1}, NestList[x + (x = #) &, 0, n - 1]]

fibonacciList2
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

The last one merely needs the proper seed:

LinearRecurrence[{1, 1}, {0, 1}, 10]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

Finally, taking the question at face value you can modify your code to return fPrev rather than fNext to start from zero:

fibonacciSequence[n_] :=
Module[{fPrev = 0, fNext = 1, i = 0},
While[i++ < n, {fPrev, fNext} = {fNext, fPrev + fNext}];
fPrev
]

Array[fibonacciSequence, 10, 0]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

$fibList = {0, 1}; fibonacciList[n_] /; n <= Length@$fibList := Take[$fibList, n] fibonacciList[n_] :=$fibList =
$fibList ~Join~ Module[{x =$fibList[[-2]]},
Rest@NestList[x + (x = #) &, $fibList[[-1]], n - Length@$fibList]]
• For bonus points, memoize fibonacciList without harming initial performance. :D – rcollyer Sep 3 '13 at 14:52
• @rcollyer Interesting challenge. Do you have a solution? – Mr.Wizard Sep 3 '13 at 14:56
• Actually, I don't. I just wanted to poke the bear and see what came of it. I'll have to think on it. Oh, and +1, as already given. – rcollyer Sep 3 '13 at 14:59
• @rcollyer I gave it a shot. – Mr.Wizard Sep 3 '13 at 15:28
• Interestingly enough, on my machine, fibList takes 0.04s less time on first pass than fibList2 does. The second time is no contest. So, performance is the same/slightly better on initial pass. Do Not attempt fibList2; I had to kill my kernel as it ate up all remaining mem on my machine. (Where fibList -> fibonacciList.) Additionally, fibList was still approx. 0.1 s. So, unless a large number of fib nums need to be calculated, I can't see where even memoization is all that useful here. – rcollyer Sep 3 '13 at 15:47

This is probably defeating your professor's unspoken desire, but no one explicitly said you required a recursion. It may or may not entertain you to know Binet's formula. Without checking, I would guess that this approach is similar to how the built in function computes Fibonacci numbers. It is clearly computationally cheaper than any sort of recursion or nesting, and that would be noticeable deep into the sequence. This is a bit slower than the built in function, but it will do say the 3 millionth number pretty fast:

fibos[n_] := RootReduce@(((1 + Sqrt)/2)^n - ((1 - Sqrt)/2)^n)/Sqrt

This could be made much shorter with some small modicum of effort. To get your table, implement it with something like:

Table[fibos[i], {i, 0, 15}]
f[n_]:=Union @@ NestList[{{0,1},{1,1}}.# &, {1, 1}, n]

EDIT

fib[n_]:=NestList[{{0,1},{1,1}}.# &, {0, 1}, n][[All,1]]

and MatrixPower method:

fn[n_]:=First[MatrixPower[{{1,1},{1,0},n-1].{1,0}]
• Not ideal as does not produce 0,1,1. See EDIT – ubpdqn Sep 4 '13 at 10:41
• Ah, the matrix power method. That has interesting uses. +1 – Mr.Wizard Sep 4 '13 at 11:34
• @Kuba thanks I will – ubpdqn May 9 '15 at 11:39
• Using the third argument of MatrixPower[] is quite useful in this circumstance. – J. M. will be back soon May 9 '15 at 12:28

In Mathematica 10.2 one can use the new function SequenceFoldList:

fib[n_] := SequenceFoldList[Plus, {0, 1}, ConstantArray[0, n - 1]];
fib

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

Use SequenceFold to obtain just the last element.

Also taking your question at face value, but making the fix faster:

fibonacciSequence2[n_] := Module[
{fPrev = 0, fNext = 1, i = 0, list = {0}},
While[i++ < n,
{fPrev, fNext} = {fNext, fPrev + fNext};
list = {fPrev, list}
];
Reverse@Flatten[list]
]

fibonacciSequence2 // Timing

This way of constructing a list has a name, it's called linked lists.

When I compare this with Mr. Wizard's fix for the 5000 first values, I get 0.015053 seconds instead of 21.764429. (Mr.Wizard did not intend speed and I get that. His other solutions are even faster than this, I checked the last one and it took just 0.008132.)

(Also this prints the list as requested)

• +1 for an important programming tip (linked lists) – Mr.Wizard Sep 4 '13 at 11:31

This may do what you want:

Clear["`*"];
fibonacciSequence[n_] :=
Module[{fPrev = 1, fNext = 0},
Table[{fPrev, fNext} = {fNext, fPrev + fNext}, {n + 1}][[;; , 1]]
]

fibonacciSequence
(* {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610} *)

a = 1; b = 0; Table[b = a + (a = b), {10}]
NestList[{+##, #} & @@ # &, {1, 1}, 10][[;; , 1]]
Nest[#~Append~Tr@#[[-2 ;;]] &, {1, 1}, 10]
Nest[# /. {a___, x_, y_} -> {a, x, y, x + y} &, {1, 1}, 10]
Nest[{1, 1}~Join~(Most@# + Rest@#) &, {1, 1}, 10]
Nest[Accumulate[{1, 0}~Join~#] &, {}, 5]
• No love for this answer, eh? Well, you've got my vote. – Mr.Wizard Sep 4 '13 at 0:10
• @Mr.Wizard Thank you. :-) – chyanog Sep 4 '13 at 10:04
• Here's one more to add to your list: Reverse@Nest[{# + #2, ##} & @@ # &, {1, 0}, 10] – Mr.Wizard Sep 4 '13 at 10:07

Tail recursive Fibonacci sequence generator

fiboSequence[n_, a_, b_] := fiboSequence[n - 1, b, Sow[a] + b]
fiboSequence[0, a_, b_] := Sow[a]
fiboSequence[n_] := Reap[fiboSequence[n, 0, 1]][[2, 1]]

fiboSequence

$\${0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

Pattern matching Fibonacci sequence generator

fiboSequence2[n_] :=
Quiet@ReplaceRepeated[{0, 1}, {x___, a_, b_} :> {x, a, b, a + b}, MaxIterations -> n - 1]

fiboSequence2

$\${0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

For giggles, here is a contour integral method (based on Cauchy's formula) for computing the Fibonacci numbers:

Table[Round[Re[NIntegrate[1/((1 - z - z^2) z^n),
{z, 1/2, I/2, -1/2, -I/2, 1/2}]/(2 π I)]],
{n, 10}]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}

For diversity reasons:

Table[a[i] /.
RSolve[{a[n] == a[n - 1] + a[n - 2], a == 1, a == 1}, a, n][],
{i, 0, 15}]

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}

or as @J.M. ironically remarked:

Array[DifferenceRoot[
Function[{a, n}, {a[n] == a[n - 1] + a[n - 2], a == 1, a == 1}]], 16, 0]

Another natural approach is to use the built-in RecurrenceTable

RecurrenceTable[{f[n] == f[n - 1] + f[n - 2], f == 1,
f == 0}, f, {n, 0, 15}]
(* {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610} *)