0
|
5810 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
GROUPS:

# Piecewise vs If

Posted 12 years ago
 Is there a performance difference in using Piecewise vs other conditionals in a function definition.i.e. I have a function whose limit as x-> 0 is finite, but evaluates to Indeterminate when 0 is entered explicitly,myfunc[x_] := (1-Exp[-x^2])/xand I call upon this function quite a bit within Integrate calls. Is there a difference in computation speed if the function is defined asmyfunc[x_] :=  Piecewise[ {{0,0}}, (1-Exp[-x^2])/x]ormyfunc[x_] := If[x==0,0, (1-Exp[-x^2])/x]  orsome other better definition.Thanks
2 Replies
Sort By:
Posted 12 years ago
 Thanks,Greatly appreciated.
Posted 12 years ago
 If seems to be faster than Piecewise for this specific example, but defining a separate downvalue is even faster, especially when you might be able to use a literal zero rather than PossibleZeroQ. Here are some example evaluations and timings: In[25]:= numCalls = 10^4; numTrials = 10; ClearAll[myfunc1, myfunc2, myfunc3, myfunc4, myfunc5];  (* Piecewise approach *) myfunc1[x_] := Piecewise[{{0, x == 0}}, (1 - Exp[-x^2])/x];  (* If approach *) myfunc2[x_] := If[x == 0, 0, (1 - Exp[-x^2])/x];(* "Separate downvalue" approach, testing for zero *)myfunc3[_?PossibleZeroQ] = 0;myfunc3[x_] := (1 - Exp[-x^2])/x;(* "Separate downvalue" approach, assuming literal zero (exact or approximate) *)myfunc4[0 | 0.] = 0;myfunc4[x_] := (1 - Exp[-x^2])/x;(* "Separate downvalue" approach, assuming only exact zero *)myfunc5[0] = 0;myfunc5[x_] := (1 - Exp[-x^2])/x;timings = Mean /@  Table[   First@     AbsoluteTiming@      Do[       myfunc[0],       {numCalls}]/numCalls,   {myfunc, {myfunc1, myfunc2, myfunc3, myfunc4, myfunc5}},   {numTrials}]Out[36]= {2.6400*10^-6, 2.3000*10^-6, 2.0100*10^-6, 4.700*10^-7, 2.900*10^-7}Hope this helps!
Community posts can be styled and formatted using the Markdown syntax.