3
$\begingroup$

I am trying to plot a piecewise function that gets bounded above and below a certain value (e.g).

Plot[Piecewise[{{-10, -Exp[-x] + 1 <= -10}, {-Exp[-x] + 1, 
x < 0}, {Exp[x] - 1, x < 3}, {10, 
10 <= Exp[x] - 1}}], {x, -10, 10}]

The functional forms of the two pieces are -Exp[-x]+1 (for any values of that piece below 10 the function is set equal to -10) and Exp[x]-1 (for any values of that piece above 10 the value is set equal to 10. The graph should roughly look like this

Plot graph

Although the first two pieces work just fine, the third piece does not get bounded automatically and I have to use a numerical solution (x<2.3978), which might cause me issues. This is the graph I get.

Wrong plot

Does anyone know of a way to make this work? Any help you can provide will be greatly appreciated!

$\endgroup$
5
$\begingroup$

Since Piecewise gets evaluated begining from the left until the condition is True, you can simply change the position of the parts like that:

    Plot[Piecewise[
        {{-10, -Exp[-x] + 1 <= -10}, 
         {-Exp[-x] + 1, x < 0}, 
         {10, 10 <= Exp[x] - 1}, 
         {Exp[x] - 1, True}}], 
         {x, -10, 10}]
$\endgroup$
  • $\begingroup$ Thank you very much, that solves my problem in my preferred way. Can you please explain how the True condition works, and why my formulation was causing problems? $\endgroup$ – Titus Feb 20 '17 at 15:44
  • 1
    $\begingroup$ Your formulation didn't work, because like m_goldberg showed, the two parts of the curve fit together at x=2.3979. Your condition was x>3. Bringning the conditon 10<=Exp[x]-1 at the third position, it is fullfilled from x>2.3979, since testing of Piecwise begins from the left. The True at the forth part means, this parts is taken if none of the other conditions is True. $\endgroup$ – Akku14 Feb 20 '17 at 16:02
3
$\begingroup$

You need to compute where the middle section really reaches 10. The correct numerical solution is at x = 2.3979.

With[{a = NSolve[Exp[x] - 1 == 10, x, Reals][[1, 1, 2]]},
  f[x_] := 
    Piecewise[
      {{-10, -Exp[-x] + 1 <= -10},
      {-Exp[-x] + 1, x < 0},
      {Exp[x] - 1, x < a},
      {10, x >= a}}]]

Plot[f[x], {x, -10, 10}]

plot

$\endgroup$
  • $\begingroup$ I came up with a very similar solution, but I would like to avoide Solve and relying on a numerical solution because I will introduce parameters later on, which might cause errors. $\endgroup$ – Titus Feb 20 '17 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.