Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Finding the max()/min()

by etcshadow (Priest)
on Nov 11, 2004 at 04:55 UTC ( [id://406924]=note: print w/replies, xml ) Need Help??


in reply to Finding the max()/min()

Here's an interesting one that doesn involve a comparison operator (even an obfuscated one):
($x + $y + abs($x - $y)) / 2
The math behind that is: take the average of the two numbers, and then add half their difference (start half-way between, and then go up by half). So: (x+y)/2 + abs(x-y)/2, and then factor out the division by two.
------------ :Wq Not an editor command: Wq

Replies are listed 'Best First'.
Re: Finding the max()/min()
by benizi (Hermit) on Nov 12, 2004 at 21:58 UTC

    Very cool. <nitpick>...but there's still a comparison; it's just hidden in the abs() function: (roughly:) abs(x) := x >= 0 ? x : -x.</nitpick>

    [OT] Reminds me of a programming assignment where we were supposed to put the square roots of the integers from 1-100 inclusive into two groups with roughly equal sums. I used the fact that sqrt(x) + sqrt(x+3) is very close to sqrt(x+1) + sqrt(x+2) and managed to outperform all the other submissions by several orders of magnitude in both speed and "difference in sum". (Yea math!)

      The nitpick is perfectly valid... I almost made a note of it. Of course, it would be possible (though silly) to implement an abs function without a comparison, such as sub abs { sqrt($_[0]**2) }.

      There's probably some mathematical identity for the abs of the difference of two numbers... but I didn't get enough sleep last night to think about what it might be :-)

      ------------ :Wq Not an editor command: Wq
      abs(x) can be implemented mathematically as sqrt(x**2). Or it can be implemented at the memory management level by just dropping the bit that carries the negative sign. So it's not necessarily a hidden comparison.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://406924]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-03-28 16:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found