store function values for future integration
<p>I have a function H(t) returning a float. I then want to numerically compute several integrals involving this function. However, one of the integrals basically invokes the previous integral, e.g.</p>

<pre><code>from scipy.integrate import quad

def H(t):
    return t

def G1(t):
    return quad(lambda x: H(x)*H(t-x),0,1)[0]

def G2(t):
    return quad(lambda x: G1(x)*H(t-x),0,1)[0]

res = quad(G1,0,1) + quad(G2,0,1)
</code></pre>

<p>I will need to do this for a large number of functions (i.e. continue like this with G3, G4... Gn) and my end-result will depend on all of them. Since I have to compute G1 for many values of t anyway in order to perform quad(G1,0,1), is it possible to store those computed values and use them when computing quad(G2,0,1)? I could maybe try to write my own simplistic integration function, but how would I go about storing and re-using these values?</p>

<p>I guess it's exactly same as lru_cache, but since I already wrote it, might as well share:</p>

<pre><code>def store_result(func):
    def remember(t):
        if t not in func.results:
            func.results[t]  = func(t)
        return func.results[t]
    setattr(func, 'results', {}) # make dictionary to store results
    return remember
</code></pre>

<p>This is decorator that modifies function to store results to dictionary and retrieve those when they are called with the same arguments. You can modify it to suit your needs.</p>

<p>usage:</p>

<pre><code>@store_result
def G1(t):
    return quad(lambda x: H(x)*H(t-x),0,1)[0]
</code></pre>

python function store integrate