Possible Duplicate:
Plot Even Piecewise function

Based on Howell's Principles of Fourier Analysis, I found a function

$ f(x)= \begin{cases} \sqrt{|x|} & \text{ if }-\pi < x < \pi \\ f(x-2\pi) & \text{ in general } \end{cases} $

and the author seem to be able to produce a graph with Maple that is like a bun and continuous. Now my question is how can I produce the same graph of this type in Mathematica. I am aware that I can use the piecewise function but the second condition say "in general" and hence I am lost. Please give advise.


You probably want this:

f[x_] := Piecewise[{{Sqrt[Abs[x]], -Pi < x < Pi}, {f[x - 2 Pi], 
    x > Pi}, {f[x + 2 Pi], x < -Pi}}]

Plot[f[x], {x, -4 Pi, 4 Pi}]


So what I did here is to realize the recursive nature of the definition for f[x] outside the central interval, but make sure that values outside are transported back into the middle by distinguishing the positive and negative side.


As pointed out by whuber in the comment, the mathematical statement in your original case distinction is best translated into a different computational approach that avoids the recursive self-reference to f. The goal of translating x back to the "fundamental" interval $[-\pi, \pi]$ can be achieved by replacing x with Mod[x, 2 Pi, -Pi] so that without any restriction on x we can write

f[x_] := Sqrt[Abs[Mod[x, 2 Pi, -Pi]]]

leading to the same plot as above.

  • $\begingroup$ Perfect!! I didn't know I can do like this. Thanks Jens! $\endgroup$
    – Sandra
    Jan 15 '13 at 19:34
  • 4
    $\begingroup$ Cleaner and (far) more efficient is f[x_] := Sqrt[Abs[Mod[x, 2 Pi, -Pi]]], because if there is any possibility f would be applied to largish numbers, the recursive solution doesn't work. (E.g, try Plot[f[x], {x, 10^6 - 20, 10^6}].) $\endgroup$
    – whuber
    Jan 15 '13 at 19:49
  • $\begingroup$ Oh this is special. I have never seen this before, whuber. THanks. $\endgroup$
    – Sandra
    Jan 15 '13 at 19:59
  • $\begingroup$ @whuber That's actually what I wanted to write first, believe it or not. But then something told me I should stay closer to the question... Anyway, you're right of course. $\endgroup$
    – Jens
    Jan 15 '13 at 20:18
  • $\begingroup$ There would be no harm in including both solutions in your answer :-). $\endgroup$
    – whuber
    Jan 16 '13 at 0:32

Eventually, if you want to do other things with f, the Piecewise solutions by @Jens is probably best. But just note you can do it with three separate clauses:

f[x_] := Sqrt[Abs[x]] /; -Pi< x <= Pi
f[x_] := f[x -2Pi] /; Pi < x
f[x_] := f[x + 2Pi] /; x <= -Pi
Plot[f[x], {x, -4 Pi, 4 Pi}]

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