2
$\begingroup$

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

$\endgroup$
3
  • $\begingroup$ Have you looked at memoization? $\endgroup$
    – rcollyer
    Mar 3, 2013 at 14:55
  • $\begingroup$ 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)? $\endgroup$
    – Michael E2
    Mar 3, 2013 at 21:32
  • $\begingroup$ 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] $\endgroup$
    – Peter
    Mar 3, 2013 at 22:58

1 Answer 1

4
$\begingroup$

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, #]]]]&
$\endgroup$

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.