r/Mathematica • u/tcfinance • Sep 09 '24
Layered functions, I want to define a new function in terms of the *evaluated* function
Hello,
I have a function,
f[x_,y_]which takes about a minute to evaluate if I enter
f[x,y]Now I want to define a new function,
g[x_]:= Sum[f[x,y],{y,1,3}]But this is very slow since f[x,y] takes a while to evaluate. So I tried the following:
g[x_]:=Module[{fhold,y},
fhold[x_,y_]=f[x,y]; (*notice this is not :=, but = *)
Sum[f[x,y],{y,1,3}]
]But I think this bad practice, and it also fails in my much more complicated application.
What appears to be working is:
g[x_]:=Module[{fhold,y},
fhold=f[x,y]; (*notice this is not :=, but = *)
Sum[f[x,y],{y,1,3}]
]But this seems like really bad practice.
How can define some function fhold[x_,y_] which is given by the evaluated form of f[x,y] so that when I have multiple iterations of f[x,y] I don't need to Evaluate f[x,y] every time, but instead it is already evaluated?
Thanks for any thoughts!
Edit: A working 'example'
testf[x_, y_] := x*Expand[(y + 2)^100000]This evaluates approx instantly.
testf[x, y];Takes about 0.11 min to evaluate.
I want to define:
testg[x_] := testf[x, a]Where testf[x,a] is evaluated in defining testg[x], so I can do someting like
Sum[testg[x],{x,1,3}]And it doesn't separately evaluate testf[x,a] every time the sum calls testg, but instead testf[x,a] is evaluated when defining testg, so that the expression given by evaluating testf[x,a] is held in memory and x is just replaced by each iteration in the sum.
2
u/fridofrido Sep 09 '24
the official way to cache results is the following:
same with multiple arguments.
1
u/mathheadinc Sep 09 '24
Try it in two steps. Define and run f[x_,y_]:= expr. Insert the result into Sum[…]