I have a function f that is a combination of multiple other functions g_i, which themselves are combinations of other functions h_ij


If I evaluate f[0] the evaluation takes about 20 seconds, however if I define F=f[x] then run F/.{x->0} the evaluation takes about 0.01 seconds.

Is it possible to "precompute" f so I don't need to use ReplaceAll to benefit from the speed boost?

Example Code

g = Table[With[{b = i},
  Function[{x}, Values[Solve[a*b^x == I, a][[1, 1]] ] ] ],
  {i, Table[RandomComplex[], 1000]} 

f = Function[{x}, Total[Through[g[x] ] ] ];    

When running f[4] I get an evaluation time of ~0.08 seconds, but when running F=f[x]; F/.{x->4} the run time is ~0.004 seconds.

  • 1
    $\begingroup$ Could you update your code so the other can replicate the issue. $\endgroup$ – ercegovac Oct 8 '17 at 20:07
  • $\begingroup$ The actual code is about 1000 lines long, is there another way to give more info? $\endgroup$ – bicarlsen Oct 8 '17 at 20:09
  • $\begingroup$ Can you provide a relatively simple example that illustrates the issue? $\endgroup$ – bbgodfrey Oct 8 '17 at 20:14
  • 2
    $\begingroup$ Maybe, you are looking for f=Function[{x},Evaluate[g_1[x]+g_2[x]+...+g_n[x]]]? $\endgroup$ – Henrik Schumacher Oct 8 '17 at 20:18
  • $\begingroup$ What you do is essentially solve the set of equations every time. As @HenrikSchumacher suggested, use Evaluate. $\endgroup$ – ercegovac Oct 8 '17 at 20:41

Using Evaluate around the functions in f did the trick, as suggested in the comments.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.