Message Boards Message Boards

0
|
6114 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:
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])/x

and I call upon this function quite a bit within Integrate calls. 
Is there a difference in computation speed if the function is defined as
myfunc[x_] :=  Piecewise[ {{0,0}}, (1-Exp[-x^2])/x]
or
myfunc[x_] := If[x==0,0, (1-Exp[-x^2])/x] 
or
some other better definition.

Thanks
POSTED BY: T Saab
2 Replies
Thanks,
Greatly appreciated.
POSTED BY: T Saab
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!
POSTED BY: William Rummler
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract