17

How to to calculate the maximim or minimum of two numbers without using "if" ( or something equivalant to that manner)?

The above question is often asked in introductory computer science courses and is answered using this method.

Now although it is not obvious, but using absolute value is also equivalant to using an if statement e.g. defining Max(a,b) = a if a>b else b;

Besides using limits, is there another way of finding the maximum or minimum of two numbers?

jimjim
  • 9,675

5 Answers5

50

If you let $a$ and $b$ be any two numbers then,

$$\max (a,b) = \frac{1}{2}( a + b + |a-b| )$$.

elias
  • 15
ginner
  • 509
11

If $a$ and $b$ are both positive, then $$ \max(a,b) = \lim_{n\to\infty} \left(a^n+b^n\right)^{1/n}. $$

8

Whether you need an if statement to take an absolute value depends on the format in which your numbers are stored. If you're using IEEE floating point numbers, you can take the absolute value by masking out the sign bit.

joriki
  • 238,052
  • @AlexM. : this answer reduced a decisional problem into a mechanically computable problem, so that getting absolute value of a number is just process that can be applied using the representation method. – jimjim Nov 09 '16 at 14:29
2

$$ a = \frac{a + b + (a-b)((2(a-b)+1) mod 2)}{2}, a > b$$ or $$b$$ equals the same, if $$ b > a$$ Maximum

Mouvre
  • 193
1

Here’s one more formula that came from definition of discriminant of quadratic equation which is valid for real numbers:

minimum(x,y) = (x+y-sqrt(x^2-2xy+y^2))/2

The source of origin: https://github.com/ohhmm/openmind/blob/d24bd9e4c87265038d29eda475d03da391c38fd5/omnn/math/Valuable.cpp#L2449

  • that is same as $\max ( a,b) = \frac{1}{2}( a + b + |a-b| )$ , why they are reimplementing an already existing function? – jimjim Feb 02 '24 at 00:35
  • 1
    It is min, not max. May be used for arbitrary differential coding and HPC kernels generation from its formula: https://github.com/ohhmm/generator/blob/main/generator/generator.cpp – Serg Kryvonos Feb 09 '24 at 20:37