6
$\begingroup$

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) enter image description here

$\endgroup$
5
  • $\begingroup$ I can't reproduce that behavior Mathematica version 13. Can you see if adding an explicit PlotPoints option improves the situation? $\endgroup$
    – MarcoB
    Sep 7, 2022 at 18:33
  • $\begingroup$ 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... $\endgroup$
    – MathFail
    Sep 7, 2022 at 18:39
  • $\begingroup$ Try Plot[Sum[g[x, k], {k, 0, 3}] // PiecewiseExpand // Evaluate, {x, -1, 2}, AspectRatio -> 1/2] $\endgroup$
    – Bob Hanlon
    Sep 7, 2022 at 18:51
  • $\begingroup$ It doesn't work, still having those breaking spacings @BobHanlon $\endgroup$
    – MathFail
    Sep 8, 2022 at 6:45
  • $\begingroup$ Try increasing MaxRecursions that should enable smaller values for PlotPoints $\endgroup$
    – Bob Hanlon
    Sep 8, 2022 at 13:07

1 Answer 1

6
$\begingroup$
  • 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}]

enter image description here

enter image description here

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

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.