Writing conditional logic using mathematics forumla

42 Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

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