3
$\begingroup$

Let f be some function, I know that i can memoize a function so that it does not compute again previously calculated values, I can also compile the function to speed up the calculations. But how can I memoize a compiled function ? Ideally I would want to do something like this

Clear[f]
f[x_] := Total[Table[i*x + i*x^2 + i*x^3, {i, 1000000}]];
f[12.] // RepeatedTiming (* timing for the non memoized non compile function*)
Clear[f]
f = Compile[{{x, _Real}}, Total[Table[i*x + i*x^2 + i*x^3, {i, 1000000}]]];
f[12.] // RepeatedTiming  (*timing for the non memoized compiled function,this ideally should be faster than the non compiled function  *)
f[-12.] // RepeatedTiming (*timing for the non memoized compiled function,this ideally should be faster than the non compiled function   *)
Clear[f]
f[x_] := 
  f[x] = f[-x] = 
    Compile[{{x, _Real}}, 
     Total[Table[
       i*x + i*x^2 + i*x^3, {i, 
        1000000}]]]; (* This syntax is incorrect, what I am trying to say is f is a compiled function, and the result for x and -x are the same anfd should be stored*)
f[12.] // RepeatedTiming(*timing for the memoized compiled function,this ideally should be faster than the non compiled function*)
f[-12.] // RepeatedTiming(*timing for the memoized compiled function, this ideally should be "instantaneous" *)
$\endgroup$
1
  • $\begingroup$ I'd propose With[{a = Quotient[1000000 (1000000 - 1), 2]}, f[x_] := a (x (1 + x (1 + x)))]; ;) $\endgroup$ May 31, 2023 at 2:23

1 Answer 1

6
$\begingroup$

You can use a separate CompiledFunction cf as a fallback when the argument does not appear in the DownValues of f.

cf = Compile[{{x, _Real}},
   Sum[i (x + x^2 + x^3), {i, 1, 1000000}],
   CompilationTarget -> "C"
   ];

ClearAll[f];
f[x_] := f[x] = cf[x]; 

I would not use f[x_] := f[x] = f[-x] = cf[x]; as the result is not independent of the sign of the argument.

$\endgroup$
3
  • $\begingroup$ Not really addressing your question of memorizing compiled function but as an aside, note that if all you are doing is summing the table then you don't actually need apply Table and Total. Note that f[x]=(x + x^2 + x^3) 1000000 1000001 /2 $\endgroup$
    – jmm
    May 31, 2023 at 17:30
  • 1
    $\begingroup$ Thank you @jmm and Henrik Schumacher, yes the example does not make sense I just wrote some random function ! $\endgroup$
    – DarkBulle
    May 31, 2023 at 20:25
  • $\begingroup$ You‘re welcome. $\endgroup$ Jun 1, 2023 at 0:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.