![]() |
Python
1.0
|
Maximum of two numbers without conditionals. More...
Functions | |
def | maxnc (a, b) |
Return the maximum of two numbers. More... | |
def | main () |
Maximum of two numbers without conditionals.
a > b, a + b + a - b = 2a a < b, a + b - a + b = 2b max(a,b) = (a + b + abs(a-b)) / 2
def maxnc.main | ( | ) |
def maxnc.maxnc | ( | a, | |
b | |||
) |
Return the maximum of two numbers.
(a + b + math.sqrt((a-b)*(a-b))) / 2.0
Note that even square root has also a conditional test.
int max(int c1, int c2) { return c1 > c2 ? c1 : c2; }
A second approach is using bitwise operators, which works for integers.
Let nb be the number of bits in a word minus one.
(a-b)>>nb gets the sign bit
This results in:
Two complement is all bits negated plus 1.
a | first number. |
b | second number. |