I have two functions that I both use memoization for. My goal is to plot the ratio of these two functions. Since I already plot the functions by themselves, and I use memoization, it would seem to me that this shouldn't take much time. However, it still runs very slowly, suggesting to me that the memoization doesn't work as I had intended.

mem : f1[x_?NumericQ] := mem = (*slow function 1*)
mem : f2[x_?NumericQ] := mem = (*slow function 2*)
mem : f3[x_?NumericQ] := mem = f1[x]/f2[x]
Plot[f1[x], {x,0,1}]
Plot[f2[x], {x,0,1}]
Plot[f3[x], {x,0,1}]

All three plots are slow, but I would expect the third one to be fast since the relevant details have been calculated in the previous two plots. My guess is that Plot uses different x-values for the third plot than the ones that are stored in memory, possibly due to the fact that these x-values for f1 and f2 differ. Is there a way to speed up this procedure?

  • 4
    $\begingroup$ The adaptive sampling ("Plot initially evaluates f at a number of equally spaced sample points specified by PlotPoints. Then it uses an adaptive algorithm to choose additional sample points, subdividing a given interval at most MaxRecursion times.") varies between the graphs due to the different functions; consequently, the sample points are not generally the same and the memorization has limited effect. $\endgroup$
    – Bob Hanlon
    Sep 3, 2021 at 14:14

1 Answer 1


Switch off adaptive sampling: setting MaxRecursion to zero,

Clear[f1, f2, f3]
mem : f1[x_?NumericQ] := mem = (Pause[1]; x^2)
mem : f2[x_?NumericQ] := mem = (Pause[1]; x^3)
mem : f3[x_?NumericQ] := mem = f1[x]/f2[x]

Plot[f1[x], {x, 0, 1}, PlotPoints -> 10, MaxRecursion -> 0] // AbsoluteTiming
Plot[f2[x], {x, 0, 1}, PlotPoints -> 10, MaxRecursion -> 0] // AbsoluteTiming
Plot[f3[x], {x, 0, 1}, PlotPoints -> 10, MaxRecursion -> 0] // AbsoluteTiming

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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