Making Mathematica Functions Evaluate Rapidly?

*Subject*: [mg2206] Making Mathematica Functions Evaluate Rapidly?*From*: siegman at ee.stanford.edu (A. E. Siegman)*Date*: Mon, 16 Oct 1995 15:53:04 GMT*Approved*: usenet@wri.com*Distribution*: local*Newsgroups*: wri.mathgroup*Organization*: Stanford University*Sender*: daemon at wri.com ( )

I frequently want to evaluate (plot, numerically integrate, calculate numerical moments of) functions which start out complex, e.g., something like f[x,y,z] = (1/ f1[x,y,z] ) Exp[ f2[x,y,z] ] where f1[x,y,z] and f2[x,y,z] may contain various purely real coefficients, call 'em a,b,c,... which have fixed (predefined) values, as well as the variables x,y,z , and some explicit I's (the imaginary unit I), and some standard functions, e.g., Cos[], Sin[], etc.. In other words, all input values are purely real, and all I's are explicit. Then, what I really want to do is to generate purely real outputs, either g1[x,y,z] = Abs[f[x,y,z]] or g2[x,y,z] = Abs[f[x,y,z]]^2 in a form that will evaluate as rapidly as possible (on a PowerMac). What's the best way to do this? Should I define the initial functions using = or := ? At what stage should I compile (and how)? Can I compile a function that contains other functions that have already been compiled? I sometimes seem to get very small complex values coming out of the compiled versions of g1 or g2 (i.e., the Abs[] functions), even though I've used _Real on x,y,z in the compilation, which makes me think they may being evaluated with complex values even though everything is supposedly real. Do I need to use ComplexExpand somehow on f[x,y,z] to separate it into Re and Im parts, then square them independently to get Abs[]^2 ? And finally, what if Pi or Sqrt[2] or ... are also contained in the functions f1, f2 ? Do I need to do something to force those into numerical form also? (My experience is that depending on just how I set up a calculation like the above I get wildly different speeds -- but there seems to be no systematic way to know how to get the fastest evaluation.) Email replies to siegman at ee.stanford.edu appreciated -- thanks.