Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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?

share|improve this question
3  
For me the absolute value is $\sqrt{a^2}$ for real numbers. I don't see an if here. –  t.b. Aug 21 '11 at 10:29
    
Damn, that answers it –  Arjang Aug 21 '11 at 10:37
    
if you knew what range your numbers are from you could use something along the lines of counting sort - as far as i understand it, it unambiguously only uses 'arithmetic operations' –  Peter Sheldrick Aug 21 '11 at 10:38
    
Even earlier... –  J. M. Aug 21 '11 at 10:40
    
Theo, i think then the question becomes: what is the most 'efficient' way to evaluate $\sqrt(a^2)$? - clearly in this case then the answer becomes 'if a > 0: +a else -a' –  Peter Sheldrick Aug 21 '11 at 10:48

4 Answers 4

up vote 8 down vote accepted

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.

share|improve this answer

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

$$\max (a,b) = 1/2( a+ b+ |a-b| ).$$

share|improve this answer
    
Very nice one... –  Emmad Kareem Jul 27 '12 at 15:50
    

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

share|improve this answer

if u want minimum or maximum number without if-else then check this http://innosen.blogspot.in/2013/04/find-maximum-or-minimum-of-two-numbers.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.