5

I have a Piecewise function consisting of two rectangle waves with different duty cycles:

dc1 = 0.7; dc2 = 0.3; period = 1; maxt = 15; 
rectangleWave[t_, period_, duty_] := UnitBox[Mod[t/period, 1.]/(2. duty)]; 
pwm1[t_] := rectangleWave[t, period, dc1]; 
pwm2[t_] := rectangleWave[t, period, dc2]; 
pwm[t_, tsplit_] := Piecewise[{{pwm1[t], t < tsplit}, {pwm2[t], t >= tsplit}}];
Plot[pwm[t, 5], {t, 0, maxt}, Exclusions -> None, PlotRange -> All]

enter image description here

but if I increase my Plot interval beyond 16 I get

enter image description here

Looks like there's an error in my definition of rectangleWave. However, when I use the Piecewise function in a differential equation it is interpreted correctly:

dc1 = 0.7; dc2 = 0.3; period = 1; y0 = 0.65; maxt = 18; 
rectangleWave[t_, period_, duty_] := UnitBox[Mod[t/period, 1.]/(2. duty)];
pwm1[t_] := rectangleWave[t, period, dc1]; 
pwm2[t_] := rectangleWave[t, period, dc2]; 
pwm[t_, tsplit_] := Piecewise[{{pwm1[t], t < tsplit}, {pwm2[t], t >= tsplit}}];
c1 = 1; r1 = 2; 
s = NDSolve[{r1 c1 y'[t] + y[t] == pwm[t, 5], y[0] == y0}, y, {t, 0, maxt}];
Plot[{pwm[t, 5], Evaluate[y[t] /. s]}, {t, 0, maxt}, 
        Exclusions -> None, PlotRange -> All]

enter image description here

Ideas anyone?

stevenvh
  • 6,866
  • 5
  • 41
  • 64

2 Answers2

12

Looks as if it might be that you need to increase the number of points plotted, as in:

Plot[pwm[t, 5], {t, 0, maxt}, Exclusions -> None, PlotRange -> All, PlotPoints -> 100]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
bill s
  • 68,936
  • 4
  • 101
  • 191
3

This problem crops up again and again. A better understanding of Mathematica's plot algorithm and options will prevent it from being a surprise. I highly recommend reading the great answers to these questions:


I realize this answer is in essence a couple of links, and such answers are discouraged. Nevertheless the alternatives in this case appear less desirable. The decision has been made not to migrate the linked questions.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371