RE: Recovering f[z] values?
- To: mathgroup at smc.vnet.net
- Subject: [mg42719] RE: [mg42692] Recovering f[z] values?
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Wed, 23 Jul 2003 00:25:12 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: AES/newspost [mailto:siegman at stanford.edu] To: mathgroup at smc.vnet.net >Sent: Monday, July 21, 2003 11:15 AM >To: mathgroup at smc.vnet.net >Subject: [mg42719] [mg42692] Recovering f[z] values? > > >During the course of a long notebook evaluation a certain function > > f[z] = some function of z > >gets executed multiple times for various values of z which are >no longer >remembered. Near the end of the calculation it's desired to >recover all >these values, perhaps in a list > > {{z1,f[z1]}, {z2,f[z2}, . . . } > >Is there a simple way to do this? > Dear Professor Siegman, the suggestions given so far memoize the call arguments with the function values calculated at the definition of the function. The advantage of this is (and this usually is the reason to memoize) that a repeated call with an argument already given, avoids recalculation and retrieves the already calculated value transparently to the user. The disadvantage is (or may be, depends on your application) to loose the call sequencing information, you cannot reconstruct the {z, f} path. If you want to do so, you may adjust the method proposed like this: In[29]:= Clear[f, mem] In[30]:= f[z_] := Last[mem[++i] = {z, f0[z]}] use f: In[31]:= i = 0; f /@ Table[Random[Integer, {0, 20}], {5}] Out[31]= {f0[16], f0[7], f0[20], f0[3], f0[3]} retrieve {z, f}: In[32]:= mem /@ Range[i] Out[32]= {{16, f0[16]}, {7, f0[7]}, {20, f0[20]}, {3, f0[3]}, {3, f0[3]}} For the next run, of course, Clear[mem] and reset i = 0. f0[z] is the rhs of the definition for f, you have used so far. Of course you are free to additionally memoize the function (for performance), but its a bit tricky to keep the counter: In[73]:= Clear[f, mem] In[74]:= f[z_] := f[z] /; (mem[++i] = z; True) = (mem[++i] = z; f0[z]) run: In[75]:= i = 0; f /@ Table[Random[Integer, {0, 20}], {10}] Out[75]= {f0[0], f0[10], f0[3], f0[20], f0[18], f0[15], f0[3], f0[13], f0[1], f0[15]} retrieve: In[76]:= With[{z = mem[#]}, {z, f[z]}] & /@ Range[i] Out[76]= {{0, f0[0]}, {10, f0[10]}, {3, f0[3]}, {20, f0[20]}, {18, f0[18]}, {15, f0[15]}, {3, f0[3]}, {13, f0[13]}, {1, f0[1]}, {15, f0[15]}} With this, for the next run also reset the DownValues of f, e.g. as Bob Hanlon has suggested. -- Hartmut Wolf