Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid repeated calls to Interpolation

I want to interpolate a function in mathematica.

The function depends on a parameter a, in fact it is the inverse of a function F which also depends on a, so I build my approximation as follows,

approx = Interpolation[Table[{F[0.1 n, a], 0.1 n}, {n, -100, 100}]]

now I can simply call approx[x] to evaluate the inverse function at a point.

Instead I would like to do something like this: Define a function which takes a parameter,

G[x_,a_] = "construct the interpolating function,
            and return the value of the function at x"

Then write G[x,a] to evaluate the function. Otherwise I would have to repeat the interpolation for all the parameters I am interested in and have lots of variables lying around. I have tried putting the Interpolation[] call inside a module but that just constructs the interpolation every time I call G[x,a]! How would I avoid this?

Thanks for reading.

like image 948
mark Avatar asked Oct 16 '11 02:10

mark


1 Answers

The first step is to parameterize approx with a:

approx[a_] := Interpolation[Table[{F[0.1 n,a],0.1 n},{n,-100,100}]]

With this definition, G can then be defined thus:

G[x_, a_] := approx[a][x]

But, as observed in the question, this ends up reconstructing the interpolation every time G is called. One way to avoid this is to redefine approx using memoization:

m: approx[a_] := m = Interpolation[Table[{F[0.1 n,a],0.1 n},{n,-100,100}]]

Now, approx will save the interpolation function for any given a, avoiding reconstruction in subsequent calls with the same a. Of course, this uses up memory so if there are a large number of distinct values of a then memory could run short. It is possible to localize the cache used by approx by associating the saved values with another symbol (cache in this case):

approx[a_] := cache[a] /.
  _cache :> (cache[a] = Interpolation[Table[{F[0.1` n,a],0.1` n},{n,-100,100}]])

With this version of approx, cache can be localized using Block, e.g.:

Block[{cache}
, Table[G[x, a], {x, 0, 5}, {a, 0, 1, 0.1}]
]

The interpolation functions are still temporarily stored for each distinct value of a, but now those saved definitions are released after the Block exits.

For more information about functions with memory in Mathematica, see the SO questions:

The best way to construct a function with memory

Dynamic Programming in Mathematica: how to automatically localize and / or clear memoized function's definitions

like image 51
WReach Avatar answered Nov 25 '22 00:11

WReach