For Programmers: Free Programming Magazines  


Home > Archive > Mathematica > November 2007 > Recursive function









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Recursive function
Miguel

2007-11-29, 8:18 am

How can I accelerate the execution of the recursive function?. Perhaps
with Compile?

Szabolcs Horvát

2007-11-30, 8:21 am

Miguel wrote:
> How can I accelerate the execution of the recursive function?. Perhaps
> with Compile?


There is no magical Mathematica function that can speed up execution for
you. The function needs to be rewritten to speed it up---whether this
is possible or not depends on the actual problem.

You might find it this article useful:
<http://en.wikipedia.org/wiki/Tail_recursion>

--
Szabolcs

Jean-Marc Gulliet

2007-11-30, 8:21 am

Miguel wrote:

> How can I accelerate the execution of the recursive function?. Perhaps
> with Compile?


By using *memoization*, that is by defining functions that remember the
intermediate values they have already found. See [1] for general
information about the technique, and [2] and [3] for specific examples
applied to Mathematica.

Basically, rather than defining, say, the general term of the recursive
function f as f[n_] := body_of_the_function, you define it as f[n_] :=
f[n] = body_of_the_function, so the intermediate values are going to be
stored in the symbol f[1], f[2], ... , f[n-1], and finally f[n].

Here is an example with the classic Fibonacci sequence and the timing
for the versions without and with memoization.

(* Timing for recursive Fibonacci WITHOUT memoization *)

In[32]:= Clear[f]
f[0] = 1; f[1] = 1;
f[n_] := f[n - 1] + f[n - 2]
Table[First@Timing[f[n]], {n, 1, 40, 5}]

Out[35]= {0., 0., 0., 0.015, 0.063, 0.953, 9.516, 216.843}

(* Timing for recursive Fibonacci WITH memoization *)

In[36]:= Clear[f]
f[0] = 1; f[1] = 1;
f[n_] := f[n] = f[n - 1] + f[n - 2]
Table[First@Timing[f[n]], {n, 1, 40, 5}]

Out[39]= {0., 0., 0., 0., 0., 0., 0., 0.}

[1] "Memoization", _Wikipedia, the free encyclopedia_
http://en.wikipedia.org/wiki/Memoization

[2] "2.5.9 Functions That Remember Values They Have Found", _The
Mathematica Book Online_,
http://documents.wolfram.com/mathem...k/section-2.5.9

[3] "Functions That Remember Values They Have Found", _Mathematica
Tutorial_,
http://reference.wolfram.com/mathem...und
.html


Regards,
--
Jean-Marc

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com