# Piecewise-constant function with infinitely many pieces

How can I define the following function in Mathematica:

$$f(x)=\begin{cases} x-n,&\mbox{when 2n\le x\le 2n+1,}\\n+1,&\mbox{when 2n+1\le x\le 2n+2,}\end{cases}$$

where $n$ takes all integer values?

I tried this:

F[x_] := Piecewise[{
{x - n, 2 n <= 2 <= 2 n + 1},
{n + 1, 2 n + 1 <= x <= 2 n + 2}}]


But this apparently defines $F$ as a function of $n$, while I need it only as a function of $x$.

That $F$ should really be something like $F_n$, defining a family of functions and then your total $F$ would really be the union of the $\{F_n\}$ over the domains where they are non-zero.

Then unless I am much mistaken each of those domains will have length $2$ and so we can define your family of functions as you had above and then have a dispatcher function to the appropriate function be your union function, using Quotient

So in total it will look like:

fxn[x_, n_] :=
Piecewise[
{
{x - n, 2 n <= x <= 2 n + 1},
{n + 1, 2 n + 1 <= x <= 2 n + 2}
}
];
fxn[x_] :=
fxn[x, Quotient[x, 2]]


And we'll confirm that I have this right:

With[{maxN = 10},
{
Plot[
Evaluate@Table[fxn[x, n], {n , 0, maxN}], {x, 0, 2*maxN + 2}],
Plot[fxn[x], {x, 0, 2*maxN + 2}]
}
]


• Thanks. Now I understand also how to solve similar problems. – Erel Segal-Halevi Feb 12 '18 at 8:32
f[x_] := Min[x - Quotient[x, 2], Quotient[x + 2, 2]]
Plot[f[x], {x, 0, 20}]


One more way is as follows.

f[x_] := Sum[ Piecewise[{{x - n, 2 n <= x <= 2 n + 1}, {n + 1,
2 n + 1 <= x <= 2 n + 2}}], {n, -Infinity, Infinity}];
Plot[f[x],  {x, -4, 5}]


Another way:

ftw[x_] = (TriangleWave[x/2 - 1/4] + 2 x + 1)/4


The problem with your approach is that your Piecewise definition depends on both x and n. However, given an x value one can compute what the corresponding n is, so the following Piecewise function does what you want:

f[x_] := Piecewise[
{
{x - Floor @ Quotient[x, 2], Mod[x, 2]<=1}
},
Floor @ Quotient[x, 2] + 1
]


where I used the fact that n can be derived from x using Floor and Quotient. Here's a visualization:

Plot[f[x], {x, 0, 10}]