Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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[15] 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.

share|improve this question
1  
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
1  
@s.s.o I'd use Array[Fibonacci, 15] or Fibonacci @ Range @ 15 myself. –  Mr.Wizard Sep 3 '13 at 14:47
1  
@Mr.Wizard Anytime educative suggestions are welcome. Time to practice alternative coding :) Thank you. –  s.s.o Sep 4 '13 at 6:49
add comment

5 Answers

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] = 0; f[1] = 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[10]
{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[10]
{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}

Addendum for rcollyer:

$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]]
share|improve this answer
    
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
1  
@rcollyer I gave it a shot. –  Mr.Wizard Sep 3 '13 at 15:28
    
Interestingly enough, on my machine, fibList[50000] takes 0.04s less time on first pass than fibList2[50000] does. The second time is no contest. So, performance is the same/slightly better on initial pass. Do Not attempt fibList2[500000]; I had to kill my kernel as it ate up all remaining mem on my machine. (Where fibList -> fibonacciList.) Additionally, fibList[50000] 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
show 3 more comments
f[n_]:=Union @@ NestList[{{0,1},{1,1}}.# &, {1, 1}, n]

EDIT

fib[n_]:=NestList[{{0,1},{1,1}}.# &, {0, 1}, n][[All,1]]
share|improve this answer
    
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
add comment

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[5000] // 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)

share|improve this answer
1  
+1 for an important programming tip (linked lists) –  Mr.Wizard Sep 4 '13 at 11:31
add comment

This may do what you want:

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

fibonacciSequence[15]
(* {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]
share|improve this answer
    
No love for this answer, eh? Well, you've got my vote. –  Mr.Wizard Sep 4 '13 at 0:10
    
@Mr.Wizard Thank you. :-) –  chyaong Sep 4 '13 at 10:04
2  
Here's one more to add to your list: Reverse@Nest[{# + #2, ##} & @@ # &, {1, 0}, 10] –  Mr.Wizard Sep 4 '13 at 10:07
add comment

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[5])/2)^n - ((1 - Sqrt[5])/2)^n)/Sqrt[5]

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}]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.