Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Patrick Abraham Avatar asked Mar 10 '26 15:03

Patrick Abraham


1 Answers

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.

like image 111
Szabolcs Avatar answered Mar 13 '26 15:03

Szabolcs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!