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.
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).
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.
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.
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.)
Jefromi is right. Look at Memoization on wikipedia. They use the example of factorial and how to speed it up with memoization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With