1
$\begingroup$

This drives me crazy. Why producing the first plot is so slow?

It is exactly same as the second plot except that the colors are not the same.

(The same slow it is with Plot[Evaluate@ Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}], {x, -21, 2}] // AbsoluteTiming).

Try with 0 instaed of I then it take 30 seconds.

pl = Table[
   Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}];
Plot[pl, {x, -21, 2}] // AbsoluteTiming
Plot[Table[
   Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 
    20}], {x, -21, 2}] // AbsoluteTiming

enter image description here

$\endgroup$
1
  • $\begingroup$ Another variation: Plot[Table[ Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}], {x, -21, 2}, Evaluated -> True] is fast with individually colored curves. $\endgroup$
    – Goofy
    Apr 21 at 20:34

2 Answers 2

4
$\begingroup$

Use Exclusions -> None to turn off detecting the discontinuities, or replace Piecewise with ConditionalExpression.

$Version
(* "14.0.0 for Microsoft Windows (64-bit) (December 13, 2023)" *)

pl = Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}];

Plot[pl, {x, -21, 2}] // AbsoluteTiming // First
(* 0.403537*)

Plot[pl, {x, -21, 2}, Exclusions -> None] // AbsoluteTiming // First
(* 0.101821*)

pl2 = Table[ConditionalExpression[Sin[x] + n, -n < x < 1], {n, -20, 20}];
Plot[pl2, {x, -21, 2}, Exclusions -> None] // AbsoluteTiming // First
(* 0.0972942 *) 

Plot[Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 
     20}], {x, -21, 2}] // AbsoluteTiming // First
(* 0.0820308 *)
$\endgroup$
3
  • $\begingroup$ Note that Piecewise[{{Sin[x] + n, -n < x < 1}, {Undefined, True}}] evaluates to ConditionalExpression (thus yours is similar to azerbajdzan's). $\endgroup$
    – Goofy
    Apr 21 at 20:36
  • $\begingroup$ Not sure what you mean. I don't have any Piecewise[..., Undefined] in my code :) $\endgroup$
    – Domen
    Apr 21 at 21:07
  • $\begingroup$ You have ConditionalExpression, azerbajdzan has the Piecewise code. Why did you think I was comparing yours and theirs? :) Anyway, it's mainly for others to point out how they are related. It doesn't seem to be well-known. :) :) $\endgroup$
    – Goofy
    Apr 22 at 0:17
2
$\begingroup$

Using Undefined instead of other values solves the problem. Anyway to me it is a bug.

Plot[Evaluate@
   Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {Undefined, 
       True}}], {n, -20, 20}], {x, -21, 2}] // AbsoluteTiming

enter image description here

$\endgroup$
2
  • $\begingroup$ Yes it may be similar, I posted it before Domen's answer. $\endgroup$ Apr 21 at 20:33
  • 3
    $\begingroup$ This bug have been fixed after version 14.0 $\endgroup$
    – cvgmt
    Apr 22 at 0:28

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.