Search code examples
mathmathematical-expressions

How to implement max condition using only mathematical functions/expression?


It can be regarding any programming language.

For example in PHP:

if($x > 2) { $x=2; } 

Is there any way to not use a condition, but use some mathematical expression to reach the same result?


Solution

  • I found the answer

    $maxval = 2;
    
    $x = $maxval - (abs($maxval - $x) + $maxval - $x) / 2;
    

    so if $x > $maxval, this expression (abs($maxval - $x) + $maxval - $x) / 2; becomes 0 and $x becomes equal to $maxval else this expression is equal to $maxval - $x, and the whole equation becomes $x = $x

    but the shortest solution is

    $x = min($x, 2);