# Expressing $f(x)=-x \;\;\; -2\leq x \leq 0\\f(x)=x \;\;\; 0< x \leq 2\\f(x+4)=f(x)$ on Mathematica?

Can we express functions such as:

$$f(x)=-x \quad -2\leq x \leq 0\\f(x)=x \quad 0< x \leq 2\\f(x+4)=f(x)$$

On Mathematica? I tried something with piecewise functions but it didn't work. Namely, I couldn't make the last condition. I tried:

f[x_] := Piecewise[{{-x, -2 <= x <= 0 }, {x, 0 < x <= 2 }}]
f[x_ + 4] := f[x]

• Note that in this particular case and due to the form of the piecewise function, you can use the more straightforward f[x_]:=Abs[x] Apr 26 at 16:07
• Try f[x_]:= f[Mod[x,4,-2]] Apr 26 at 16:15
• See, for example, mathematica.stackexchange.com/a/57625/7936 and other answers to that question. Apr 26 at 19:36

Try this:

    f[x_] := Abs[TriangleWave[x/8]];
Plot[f[x], {x, -8, 8}]


with the following effect: Have fun!

• I think you need to scale (y) by 2: 2 Abs@TriangleWave[x/8] (+1) Apr 26 at 20:33
• @ Michael E2 You are right Apr 27 at 8:01

Using Piecewise

Clear[f]


To avoid an attempt at infinite recursion, the argument of f should be restricted to numeric values.

f[x_?NumericQ] := Piecewise[{
{-x, -2 <= x <= 0},
{x, 0 < x <= 2},
{f[x - 4], x > 2},
{f[x + 4], x < -2}}]

f /@ {-17.25, -1.5, 1.75, 16.5}

(* {1.25, 1.5, 1.75, 0.5} *)


Another way:

g[t_] := If[Abs[t] < 2, Abs[t], g[t - 4 Sign[t]]]


which produces the same plot as Alexei's answer.

Using the Periodic operator I wrote in this answer

Periodic[T_, offset_ : 0][f_] := f@*((Mod[#, T] - offset) &)


we can say

f = Periodic[4,2][Abs]


to get the function of interest.

Another way:

f = Interpolation[{{-2, 2}, {0, 0}, {2, 2}},
InterpolationOrder -> 1, PeriodicInterpolation -> True];
Plot[f[x], {x, -4, 6}] 