4
$\begingroup$

I would like to some programming that is very generic. Particularly I am interested in the following:

Let's say I want to write a function

fuu[t_, f_] := Integrate[Exp[a*f[q]], {q, 0, 2*Pi}] /. a -> t

where t is a real value and f some function.

Now if I run fuu multiple times for different values of t, say 1,2,3 etc. and keep the function f as Cos, it will re-run the integration multiple times, which is undesirable.

Storing values is also possible if I write

fuu[t_, f_] := fuu[t, f] = Integrate[Exp[a*f[q]], {q, 0, 2*Pi}] /. a -> t

The problem is that the results from the integration are only stored for specific values of t then. How do I store it for generic t but f fixed as Cos?

Sure one may argue why not work around this by some other techniques. But the goal in Mathematica is to have effortless code that is still fast - so does anyone have suggestions?

If someone can give me a solution. How can this solution be combined with Let's say that I would want to compile the result from Integrate to get something even better?

$\endgroup$
2
  • $\begingroup$ Have a look at this discussion. $\endgroup$ Jun 25, 2019 at 21:52
  • $\begingroup$ Thank you for the link. This is very generous of you but this does not really solve my problem because different instances in the solutions provided have to be put by hand and are not dynamically determined based on what type of problem I keep throwing at mathematica. Nevertheless I very much appreciate your comment Leonid. $\endgroup$
    – Michael
    Jun 25, 2019 at 21:58

1 Answer 1

9
$\begingroup$

partial memoization:

Clear[fuu];
fuu[f_] := fuu[f] =
  Function[t, Evaluate[Integrate[Exp[t*f[q]], {q, 0, 2*Pi}]]]

test:

fuu[Cos]
(*    Function[t$, 2 π BesselI[0, t$]]    *)

use this function for different values of t:

fuu[Cos][0.2]
(*    6.34617    *)

fuu[Cos][0.4]
(*    6.53704    *)
$\endgroup$
1
  • $\begingroup$ That is elegant. $\endgroup$
    – Michael
    Jun 25, 2019 at 22:25

Your Answer

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

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