The problem of plotting an expensive function discussed in this question caught my attention. As an exercies I tried to solve it using memoization as follows
ClearAll[fn]
fn[0, a_] = 1;
fn[xEnd_, a_] :=
fn[xEnd, a] =
Module[{xPrev},(* Find the last known xPrev such that xPrev<xEnd *) ;
fn[xPrev, a] + NIntegrate[t^(a t), {t, xPrev, xEnd}]]
In the comment (* Find the last known xPrev such that xPrev<xEnd *)
, I need to add code to find a point xPrev
such that xPrev<xEnd
and fn[xPrev,a]
is is already calculated. Basically, search within existing downvalues to see the highest xPrev
satisfying the given condition that is already solved. Afterwards, I just calculate the portion of the integral from xPrev
until the xEnd
.
My question is: What is the best way to find this particular DownValue
from within the fn? Is this in general a good practice?
Please do not focus specifically on the quoted problem. I just used it as a reference to describe the problem.
Cases[ DownValues@fn, fn[x_?NumericQ,_] :> x, Infinity]
$\endgroup$ – Jason B. Feb 6 '17 at 20:56Hold
,HoldPattern
etc. $\endgroup$ – ercegovac Feb 6 '17 at 21:22