# How I can define this staircase function?

I have a function $f:[-1,1]\to\Bbb R$ defined by

$$f(x):=\begin{cases}\frac1{n+2},&x\in\left[-\frac1n,-\frac1{n+1}\right)\cup\left(\frac1{n+1},\frac1n\right]\\0,&\text{otherwise}\end{cases}\quad \forall n\in\Bbb N$$

and I dont have a clue about how to define it in mathematica. I was searching in the language documentation and I found the function 'Piecewise' but I dont know if this can work with such a function as the above.

Some help will be appreciated, thank you.

• isn't it just f[x_] := 1/(Floor[Abs[1/x]] + 2) – george2079 Feb 7 '17 at 22:35
• suppose x=.21 for example, then 1/5<x<=1/4 so n=4 and the result is 1/6 no? – george2079 Feb 7 '17 at 22:43
• @george2079 oh, I see... I will check it. Sorry, I didnt read correctly the first time. – Masacroso Feb 7 '17 at 22:47

If you want something resembling your mathematical notation you need to do this:

f[x_] := Module[{
res = FindInstance[ (
1/(n + 1) < x <= 1/(n) ||  -1/n <= x < -1/(n + 1)  ) && n > 0,
n , Integers]
},
If[res == {}, 0, 1/(n + 2) /. First@res]]


It is very slow, but Perhaps useful for more complicated cases.

• Thank you very much. I will use surely for future setups. – Masacroso Feb 7 '17 at 23:04
f[x_, n_Integer] :=
If[(-1/n <= x < -1/(n + 1)) || (1/n < x <= 1/(n + 1)),
Evaluate[1/(n + 2)], 0];

• Sorry but the function you are trying to represent is undefined, because $n$ is not defined, but in my function $n$ is defined as any natural number. – Masacroso Feb 7 '17 at 22:38
• Ooopss... a simple slip, easily corrected in the answer. – David G. Stork Feb 7 '17 at 23:10
fun[x_] := 1/(Floor[1/Abs[x]] + 2)
fun[x_] := 0 /; Abs[x] > 1
Plot[fun[x], {x, -1, 1}, Exclusions -> None, Frame -> True,
GridLines -> {1/# & /@ Range[-10, -1]~Join~Range, None}] 