2
$\begingroup$

While working on answer for question (here) I found out that the Plot is incredible slow for Piecewise function:

Some preparations:

\[ScriptCapitalD]1 = 
 TransformedDistribution[Log[u], 
  u \[Distributed] UniformDistribution[{1, 2}]]
(* TransformedDistribution[
 Log[\[FormalX]], \[FormalX] \[Distributed] 
  UniformDistribution[{1, 2}]] *)

\[ScriptCapitalD] = 
 TransformedDistribution[
  u + v, {u \[Distributed] UniformDistribution[{1, 2}], 
   v \[Distributed] \[ScriptCapitalD]1}]
(* TransformedDistribution[
 u + v, {u \[Distributed] UniformDistribution[{1, 2}], 
  v \[Distributed] 
   TransformedDistribution[
    Log[\[FormalX]], \[FormalX] \[Distributed] 
     UniformDistribution[{1, 2}]]}] *)

This looks perfectly fine:

s[x_] := PDF[\[ScriptCapitalD], x]    
pw[x_] := PiecewiseExpand[s[x], 1 <= x <= 2]
pw[x] // InputForm
(* Piecewise[{{1, x >= 1 + Log[2]}, {(-E + E^x)/E, Inequality[1, Less, x, Less, 
    1 + Log[2]]}}, 0] *)

But, the Plot is extremely slow and never finishes:

Plot[pw[x], {x, 1, 2}]

But, if I copy InputForm of pw, it magically started working:

pw2[x_] := 
 Piecewise[{{1, x >= 1 + Log[2]}, {(-E + E^x)/E, 
    Inequality[1, Less, x, Less, 1 + Log[2]]}}, 0]

Plot[pw2[x], {x, 1, 2}]
(* produces plot *)

Using Mathematica 12.1.

$\endgroup$
1
  • 1
    $\begingroup$ If you had done pw[x_] = PiecewiseExpand[s[x], 1 <= x <= 2] (i.e. use Set[] instead of SetDelayed[]), you would not have encountered this problem. $\endgroup$ Apr 17, 2020 at 13:44

1 Answer 1

4
$\begingroup$

Try

 Plot[Evaluate@pw[x], {x, 1, 2}]

Mathematica graphics

$\endgroup$
2
  • 1
    $\begingroup$ Ok, it works. But why? I can't see Piecewise having any Hold. $\endgroup$
    – m0nhawk
    Apr 15, 2020 at 17:01
  • 4
    $\begingroup$ @m0nhawk plot has Hold property. Plot has attribute HoldAll and evaluates f only after assigning specific numerical values to x. $\endgroup$
    – Nasser
    Apr 15, 2020 at 17:03

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.