I'm looking at an efficient and fast way to compute the results of a finite summation
$$\sum_{i=0}^Mf_ig_i\,. $$
I noticed that simply applying
Expand/@Sum[f[i]Expand/@g[i],{i,0,M}]
is not very efficient time-wise. The function f is generated recursively for any integer argument. I already use memoization when computing the functions recursively. They look like this
g[0] = 1;
g[n_] := g[n] = Expand@Sum[2^s, {s, 0, n - 1}];
Where do you think is the most consuming part?
f[0] = 1;
f[1] = Sum[Gamma[n] \[Alpha]^n, {n, 1, M}] + O[\[Alpha]]^(M + 1);
f[n_] := f[n] = (f[n - 1] + O[\[Alpha]]^M) (f[1] + O[\[Alpha]]^M)
- The evaluation of the functions f and g? Is there a way to save the value is an efficient way? A noticed that writing the values into a list (creating "fList" and "gList") using Table is also very timeconsuming.
- Using the function Sum? Would using Fold and pure functions be more efficient? (I tried but I didn't manage to write this sum using pure functions into the Fold function....)
f[1]
. If you define it before defining numerical value ofM
, then Mathematica will evaluateSum
from RHS off[1]
definition to a generalDifferenceRoot
expression, which will be evaluated in each non-memoized call tof
function, making them terribly slow. If you definef[1]
after definingM
, thenf[1]
will be ordinarySeriesData
expression and evaluation will be much faster. It would be best to avoid global variable in function definition and usem
as second argument off
. $\endgroup$