# Weird output when plot piecewise continuous and periodic functions

I refer to this post and try to plot a piecewise continuous and periodic function. This periodic function is defined as following:

$$h(x)=|x|, x\in [-1,1] , ~h(x+2)=h(x)$$

$$f_n(x)=\frac{1}{2^n}h(2^n x),~~~~g(x)=\sum_{n=0}^\infty f_n(x)$$

I want to plot $$g(x)$$. Here I only plot for the sum of first four terms, namely $$g_3(x)=f_0(x)+f_1(x)+f_2(x)+f_3(x)$$.

f[x_, n_] :=
Piecewise[{{1/2^(n - 1) - x, 1/2^n <= x < 2/2^n}, {x, 0 <= x < 1/2^n}}]

g[y_, n_] := f[Mod[y, 1/2^(n - 1)], n]

Plot[Sum[g[x, k], {k, 0, 3}], {x, -1, 2}, AspectRatio -> 1/2]


But why I got those breaking spacing for those lines in the graph? (I use Mathematica 10.0)

• I can't reproduce that behavior Mathematica version 13. Can you see if adding an explicit PlotPoints option improves the situation? Sep 7, 2022 at 18:33
• Thank you for the suggestion. Yes, after I set PlotPoints->5000, there is no those gaps anymore, but this will make the running very slow to generate the plot. I don't understand why this happens... Sep 7, 2022 at 18:39
• Try Plot[Sum[g[x, k], {k, 0, 3}] // PiecewiseExpand // Evaluate, {x, -1, 2}, AspectRatio -> 1/2] Sep 7, 2022 at 18:51
• It doesn't work, still having those breaking spacings @BobHanlon Sep 8, 2022 at 6:45
• Try increasing MaxRecursions that should enable smaller values for PlotPoints Sep 8, 2022 at 13:07

• It it recommended to use Mod to do with period functions.
• Since h defined from -1 to 1,it's period is equal to 2 and start from -1,so we use Mod[x,2,-1].
Clear[h, f, g];
h[x_ /; -1 <= x <= 1] = Abs[x];
h[x_] := h[Mod[x, 2, -1]]
f[x_, n_] := h[2^n x]/2^n;
g[x_, n_] := Sum[f[x, k], {k, 0, n}]
Plot[g[x, 3], {x, -1, 2}]
Plot[g[x, 10], {x, -1, 2}]


• Great, thank you! This one works, and in your second line, what does "h[x_ /; " mean? Sep 8, 2022 at 9:00
• @MathFail /; is the function Condition[] Sep 8, 2022 at 12:22
• Thank you very much! Sep 9, 2022 at 5:19