I'm working on an application which has a specific function which receives 2 ints: x and y. If y > x then I would like the function to return y otherwise return x - y. Just a few examples:
- f(10, 12) => 12
- f(9, 9) => 0
- f(11, 3) => 8
I can easily do this using ifs etc but I was just wondering if it's possible to write it using mathematics only? to be more precise what I'm asking is: is it possible to write that function as a computer function only using mathematical operands? (no ifs or any other conditionals)?
It's not any kind of homework, just pure curiousity
I was even struggling with giving it the right tags since I have no idea to what topic this issue belongs to
Thanks in advance
It's possible if you allow the absolute value 'operation'. This works except for the case when $x=y$: $$f(x,y)=y-\dfrac12\left(1-\dfrac{y-x}{|{y-x}|}\right)(2y-x)$$
I've no idea what to do if the inputs were real numbers, but because you've restricted them to integers we can hack it thus:
$$f(x,y)=y-\dfrac12\left(1-\dfrac{y-x-\frac12}{\left|{y-x-\frac12}\right|}\right)(2y-x)$$
Mathematically, it's perfect (for integer inputs). In the real world of computer arithmetic, we'd need $x$ and $y$ to be promoted to real numbers for the inner division, and the inner division converted back to an integer immediately afterwards $\dots$ and the rest of the operations are done as integers, the multiply by $\dfrac12$ turned into $\div 2$. Depending on the precision of your real & integer data types, this could fail for very positive or very negative values of $y-x$.