0

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:

  1. f(10, 12) => 12
  2. f(9, 9) => 0
  3. 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

Gideon
  • 103
  • $ f(x,y)= \begin{cases} y & y>x\ x-y & \text{otherwise}\ \end{cases} $ – barak manos Feb 25 '16 at 10:20
  • 1
    @barakmanos I obviously thought of that but I was wondering if I can write a computer program using mathematical operands only (without the regular ifs) – Gideon Feb 25 '16 at 10:23
  • 1
    The best thing i can come up with is : $f(x,y)=y+H(x-y)(x-2y)$ where H is the Heaviside function, which if defined with ifs... – nicomezi Feb 25 '16 at 10:40

2 Answers2

1

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$.

Frentos
  • 3,041
  • This answer seems to be the most elegant. I tried upvoting the other (great) answers but my reputation is too low for that. Thanks :) – Gideon Feb 25 '16 at 12:40
0

If both x and y are represented in 2's-complement format:

int func(int x,int y)
{
    int b = ((x-y)>>31)&1;
    return y*b+(x-y)*(1-b);
}

Please note that I've assumed that the size of int is 32 bits.

Generally, 31 should be replaced with sizeof(int)*CHAR_BIT-1.

It might fail if x-y overflows (extremely small or extremely large).

barak manos
  • 43,109