# Complicated condition inside piecewise function

I want to define the piecewise function

$$f(x)=\begin{cases}-1,&x\ge1\\\frac1n,&\frac1{n+1}\le x<\frac1n,\; n\in\Bbb N_{>0}\\0,&x\le 0\end{cases}$$

in this form, but I don't know if this is possible (I know that we can define this function using a ceil function, but I'm trying to see if it is possible to write the function in the above form).

The problem is that I don't know if it is possible to define the condition

$$\frac1{n+1}\le x<\frac1n,\; n\in\Bbb N_{>0}$$

f[x_] := Piecewise[{{-1, x >= 1}, {0,
x <= 0}, {1/Quiet@Reduce[1/(n + 1) <= x < 1/n, n, Integers][[2]],
0 < x < 1}}]

f[0.4]


1/2

a = RandomReal[1, 10]


{0.946522, 0.753738, 0.520006, 0.50627, 0.684279, 0.57814, 0.470449, 0.860181, 0.639912, 0.0999967}

f /@ a


{1, 1, 1, 1, 1, 1, 1/2, 1, 1, 1/10}

Another way is as follows.

f = Function[x, Piecewise[{{-1, x > 1}, {0, x <= 0}, {1/Floor[1/x], x > 0 && x <= 1}}]]

• Well, I explicitly said that Im not interested in this answer. And the expression you put here is not equivalent to the definition of the original function. You must use a ceil function of the kind $$\frac1{\lceil x^{-1}-1\rceil}$$ not a floor one. Observe that $\lfloor z\rfloor\neq\lceil z-1\rceil$ for $z$ real. – Masacroso Nov 4 '16 at 15:24
• @Masacroso: Thank you for the correction. – user64494 Nov 4 '16 at 16:07

this I think is a little closer to the actual statement:

f[x_?NumericQ] := Piecewise[{{-1, x >= 1}, {0, x < 0},
Module[{n,nn},
{1/nn,
(nn = n /. First@FindInstance[ 1/n >= x > 1/(n + 1) , n, Integers, 1]) >  0 }]}]


note the order of evaluation allows us to use the result of the logical test in the returned expression.