I'm looking at ways to get the max/min value of two numbers without using conditional statements, I found these two functions:
int Max(int x, int y)
{
return (float)(x + y) / 2.0 + abs((float)(x - y) / 2);
}
int Min(int x, int y)
{
return (float)(x + y) / 2.0 - abs((float)(x - y) / 2);
}
While they do work, what is the mathematical reason/proof behind them? why do they work?
In mathematical notation:
$$\max(x,y)=\frac12(x+y)+\frac12|x-y|$$ $$\min(x,y)=\frac12(x+y)-\frac12|x-y|$$
Without loss of generality, assume that $x>y$. Then, $$\max(x,y)=\frac12(x+y)+\frac12|x-y|=\frac12(x+y)+\frac12(x-y)=x.$$
Similarly, assuming $x>y$, then, $$\min(x,y)=\frac12(x+y)-\frac12|x-y|=\frac12(x+y)-\frac12(x-y)=y.$$
This is what you should expect, seeing as though $|x-y|=x-y$ for $x>y$.