开发者

How to compute recursion relations in mathematica efficiently?

开发者 https://www.devze.com 2023-02-03 22:58 出处:网络
I have a recursion to solve for. f(m,n)=Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]

I have a recursion to solve for.

f(m,n)=Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]
f(0,n)=1, f(1,n)=n

However, the following mma code is very inefficient

f[m_, n_] := Module[{},
  If[m < 0, Return[0];];
  If[m == 0, Return[1];];
  If[m == 1, Return[n];];
  Return[Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], 开发者_开发技巧{i, 2, n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]];]

It takes unbearably long to compute f[40,20]. Could anyone please suggest an efficient way of doing this? Many thanks!


Standard trick is to save intermediate values. The following takes 0.000025 seconds

f[m_, n_] := 0 /; m < 0;
f[0, n_] := 1;
f[1, n_] := n;
f[m_, n_] := (f[m, n] = 
    Sum[f[m - 1, n - 1 - i] + f[m - 3, n - 5 - i], {i, 2, 
       n - 2*m + 2}] + f[m - 1, n - 3] + f[m - 3, n - 7]);
AbsoluteTiming[f[40, 20]]
0

精彩评论

暂无评论...
验证码 换一张
取 消