# Speeding up code by avoiding repeated evaluation of a function

I want to speed up my code and I have two ideas, but I don't know how I can implement them. Here is a little part of my code, which I want to improve:

   R[FK_, f_] :=
FixedPoint[
Integrate[PDF[f, x]*x , {x, 0, id[Q[FK, #], #]}]
*If[CDF[f, id[Q[FK, #], #]] == 0., 0.1, CDF[f,id[Q[FK, #], #]]]
*id[Q[FK, #], #] &
, seedR] ;


1) You can see that the function is evaluated id[Q[FK, #], #] 3 times. That is unecassary. Normaly I would use a Module structure, define a new variable idd = id[Q[FK, #], #], like

    R2[FK_, f_] :=
Module[{iddd},
FixedPoint[
iddd = id[Q[FK, #], #] &;
Integrate[PDF[f, x]*x , {x, 0, iddd}]
*If[CDF[f, iddd] == 0., 0.1, CDF[f, iddd]]
*iddd &
,seedR]];


but this does not work. Do you have any idea?

2) Probably a easy one:

    If[CDF[f, id[Q[FK, #], #]] == 0., 0.1, CDF[f, id[Q[FK, #], #]]]


This involves the funtion CDF[f, id[Q[FK, #], #]] two times. One time should be enough. How can I do this?

Thanks

Peter

• Have you looked at memoization? – rcollyer Mar 3 '13 at 14:55
• For 2), If[# == 0., 0.1, #]&@CDF[f, id[Q[FK, #], #]] will evaluate the CDF once and plug it into the If statement. For 1) it looks like there might be an extra & (fourth line)? – Michael E2 Mar 3 '13 at 21:32
• Thanks for 2). It works. For 1) I produces a minimal example: The result is 2 for the working example: R[seedR_] := FixedPoint[ Integrate[Sqrt[#], {x, 0, 2}] &, seedR] But if I add another line it does not work anymore: R[seedR_] := FixedPoint[idd = # &; Integrate[Sqrt[idd], {x, 0, 2}] &, seedR]  – Peter Mar 3 '13 at 22:58

Multiple evaluations can often be avoided by using With. You might try something like
f = With[{q = Q[FK, ....]}, If[CDF[f, id[is, q, #]] == 0., 0.1, CDF[f,id[is, q, #]]]]&