0
$\begingroup$

Suppose I have a function that returns a polynomial in x,

GetPoly[params_,x_]:=GetPoly[params,x]...

but it is quite slow, so I memoize this. However, doing GetPoly[params,2y] or similar do not utilize the memoized data, it does the same computation now with 2y.

What is the best way to reuse the existing computation?

The solution I can cook up is to use an auxiliary function that computes the polynomial symbolically, and then substitute with the actual symbol/value:

GetPoly[params_,x_]:=AuxPoly[params,y]/.{y->x};
AuxPoly[params_,x_]:=AuxPoly[params,x]...

Is this the best solution to my problem? What is the convention to do this in a package?

$\endgroup$
  • 1
    $\begingroup$ Does the calculation of the polynomial change at all based on x, or only the parameters? That is, is there ever a case where to get from GetPloy[params1, x1] to GetPloy[params1, x2] is more complicated than simply substituting x2 for x1? $\endgroup$ – Jason B. Mar 11 '16 at 16:08
  • $\begingroup$ It is not clear how your code looks like so maybe this question dealing with a memoization technique for certain polynomials: Why does Expand not work within a function? and answers providing correct implementations will be helpful. $\endgroup$ – Artes Mar 11 '16 at 16:21
  • 1
    $\begingroup$ Seen this? $\endgroup$ – J. M. is away Mar 11 '16 at 16:22
  • $\begingroup$ @JasonB: Simply substituting. That's exactly what happens. But different params give different polynomials. $\endgroup$ – Per Alexandersson Mar 11 '16 at 17:27
  • 1
    $\begingroup$ @PerAlexandersson Then I would definitely do it the way you have at the end of the post. $\endgroup$ – Jason B. Mar 11 '16 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.