2-arguments function computing the order

35 Views Asked by At

I am seeking a function taking two positive integer inputs $a$ and $b$ where:

  • $f(a,b)=1$ if $a>b$

  • $f(a,b)=0$ if $a$ and $b$ are equal

  • $f(a,b)=-1$ if $a<b$.

This function should use only simple operators (that is, no absolute value, no comparator $<$ and $>$, and no characteristic function).

Is this possible ?

Thank you.

2

There are 2 best solutions below

1
On

$\DeclareMathOperator{\sgn}{sgn}$ The function you want is $\sgn(a-b)$ where $\sgn(x):\begin{cases}\dfrac x{|x|}& x\neq 0\\0& x=0\end{cases}\quad$ is the sign of $x$.

Note that $|x|$ can be defined as $\sqrt{x^2}$ without any "if".

The problem is that the value in $0$ is set arbitrary, so it cannot arise magically without using at least one if-related function (min, max, floor, characteristic function, heaviside, dirac, etc...).

The best you can hope for is an approximation, for instance $n\gg 1\quad f_n(a,b)=\dfrac{n(a-b)}{1+n\sqrt{(a-b)^2}}$

With $\lim\limits_{n\to\infty}f_n(a,b)=\sgn(a-b)$


Note: sometimes you would possibly see people using $0^x$ in place of $\begin{cases} 0 & x>0\\ 1&x=0\end{cases}$

With this convention (far from being universally shared) then $f(a,b)=\dfrac{0^{|a-b|}+a-b}{0^{|a-b|}+|a-b|}-0^{|a-b|}$ would work.

You can see, that as soon as we accept a function that "embed" an if in its core definition (even if it is hidden) then there is no problem in defining another step function like $\sgn$.

This may appear anecdotic but the C function pow actually displays this behaviour, so the $f$ above is perfectly computable.

1
On

If absolute value is disallowed, I think the best we can do is $$f(x) \approx \tanh (k(a-b))$$

where $k$ is a large number of your choosing, say $10^5$.