Your function is discontinuous. All mathematical operations usually implemented in programming languages, such as addition, multiplication, exponentiation etc. are continuous. Thus there cannot be a fully mathematical solution to your problem; every solution must involve some trick to deal with the discontinuity. Mixedmath's proposal does this by treating the case $x=y$ separately, e.g. by an exception.
If your language uses IEEE-like floats and allows bitwise float-to-int conversions and bit shifts, you could convert your float to an int bitwise and shift the sign bit to the least significant bit. In C, you could compute your function something like this:
double d = x - y; unsigned long f = 1 - ((* (unsigned long *) &d) >> 63);
(assuming that both double
and unsigned long
are 64-bit types). In Java, it would be
long f = 1 - (Double.doubleToLongBits (x-y) >>> 63);
(where you need the logical right-shift operator >>>
, not the arithmetic one >>
).
Note that any efficient implementation of the absolute value operation used in mixedmath's solution would also have to work on this level, by masking out the sign bit of IEEE-style floats; as mixedmath pointed out, a high-level implementation that compares against $0$ wouldn't avoid a comparison.