Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Fibonacci

f[0] = 0;
f[1] = 1;
f[x_] := f[x-1] + f[x-2]

This function is running slow in Mathematica and I need to increase the speed. I have to use functional programming and recursion. I'm not sure why this is running so slow, and even the slightest idea how to improve this would be helpful.

like image 885
Jon Avatar asked Nov 09 '10 03:11

Jon


People also ask

What's the time complexity of Fibonacci?

The time complexity of the Fibonacci series is T(N), i.e., linear. We have to find the sum of two terms, and it is repeated n times depending on the value of n. The space complexity of the Fibonacci series using dynamic programming is O(1).

What is so special about Fibonacci numbers?

The Fibonacci sequence is a famous group of numbers beginning with 0 and 1 in which each number is the sum of the two before it. It begins 0, 1, 1, 2, 3, 5, 8, 13, 21 and continues infinitely.

How is Fibonacci used in real life?

The number of petals in a flower consistently follows the Fibonacci sequence. Famous examples include the lily, which has three petals, buttercups, which have five (pictured at left), the chicory's 21, the daisy's 34, and so on.


2 Answers

A good way to write a faster recursive function is to have it memorize previous values. This does come at the cost of memory, of course, but it can help in cases like this. In order to calculate f[x], you calculate f[x-1] and f[x-2] - and then to calculate f[x-1], you calculate f[x-2] again; you end up recalculating a lot of values a lot of times. (Forgive my imprecision!)

To store things as you go, you can use this idiom:

f[x_] := ( f[x] = (* calculation of f[x] goes here *)  )

Edit: I don't have mathematica on this machine, but I'm pretty sure there's no way this computes the wrong value.

f[0] = 0;
f[1] = 1;
f[x_] := ( f[x] = f[x-1] + f[x-2] );

f[256]

Like I said in a comment below, if you have other definitions of f, you might want to wipe them out first with Clear[f].

Thanks to rcollyer: Be careful about $RecursionLimit! It defaults to 256. (Of course, this is with good reason. Really deep recursion is usually a bad idea.)

like image 52
Cascabel Avatar answered Sep 22 '22 01:09

Cascabel


Jefromi is right. Look at Memoization on wikipedia. They use the example of factorial and how to speed it up with memoization.

like image 22
Bradley Kreider Avatar answered Sep 23 '22 01:09

Bradley Kreider