Search code examples
recursionwolfram-mathematicawolfram-language

Wolfram-Cloud/Mathematica, effective working with recursive functions


I am working with Чебышёв-polynomials at the moment, recursive defined polynomials. For the very likely case you never saw them before:

f[0,x_]  := 1;
f[1,x_]  := x;
f[n_,x_] := 2 * x * f[n-1, x] - f[n-2, x];
Plot[{f[9, x],f[3, x]},{x, -1, 1}]

And I found myself asking, since I usually work with python, if there is a way to build an array of functions in wolfram-cloud, to ease the process.

Thus I have to calculate every f[n] only once, allowing me to improve the run-time quite a bit and also allowing me to extend the range of n.


Solution

  • Use memoization.

    In this case memoization is trickier than usual because we work with functions, not function values.

    Clear[cheb]
    cheb[0] = 1 &;
    cheb[1] = # &;
    cheb[n_] := cheb[n] = Evaluate@Expand[2 # cheb[n - 1][#] - cheb[n - 2][#]] &
    

    The Evaluate makes sure that the insides of the Function get evaluated even before supplying and argument.