philihp All American 8349 Posts user info edit post |
Using only abs(n), addition, and subtraction; is it possible to construct a function that works the same as min(a,b)?
My intuition says it might be possible, but I can't seem to figure out a way. 4/21/2009 6:07:15 PM |
OmarBadu zidik 25071 Posts user info edit post |
without doing a lot of checking doesn't this work? i'm assuming if statements are allowed
newmin(a, b){ if (a==b) { return a } if ((a-b) < (b-a)) { return a } { else return b } } ]] 4/21/2009 6:11:20 PM |
philihp All American 8349 Posts user info edit post |
Well, I guess I should have said, do it in one line; as if with an inline #define function. Or in an SQL query....
but just figured it out myself it's pretty simple. needs division though.
the motivation for needing this in the first place is because Oracle doesn't have min(a,b) built-in
[Edited on April 21, 2009 at 6:25 PM. Reason : click edit post for solution.] 4/21/2009 6:20:58 PM |
smoothcrim Universal Magnetic! 18966 Posts user info edit post |
omar's would work if you abs(a) and abs(b)
[Edited on April 21, 2009 at 6:50 PM. Reason : icwydt, concise but not especially readable] 4/21/2009 6:49:40 PM |
LimpyNuts All American 16859 Posts user info edit post |
Quote : | "newmin(a, b){ if (a==b) { return a } if ((a-b) < (b-a)) { return a } { else return b } } " |
Why not just:
if ( (a-b) > (b-a) ) then { return b } else { return a }
No need to check a==b because it's not a separate branch. Does Oracle have an If() function?
if((a-b) > (b-a), b, a) 4/21/2009 7:27:35 PM |
evan All American 27701 Posts user info edit post |
it has a CASE expression which can do if-then
[Edited on April 21, 2009 at 7:40 PM. Reason : it's more like "case when condition then thing"] 4/21/2009 7:39:13 PM |
OmarBadu zidik 25071 Posts user info edit post |
^^ good call - i missed that my first time through 4/22/2009 9:40:54 AM |
sarijoul All American 14208 Posts user info edit post |
you guys check me on this, but this is one without conditionals:
min(a,b) = 0.5*(a+b-abs(a-b))
[Edited on April 22, 2009 at 10:43 AM. Reason : simpler] 4/22/2009 10:42:20 AM |
OmarBadu zidik 25071 Posts user info edit post |
has multiplication but other than that looks good 4/22/2009 10:52:43 AM |
sarijoul All American 14208 Posts user info edit post |
i don't think there's a way to do it without multiplication. i think i even had this as a challenge problem in high school (and it said you could use abs, +, - and *). here's max if you're interested:
max(a,b) = 0.5*(abs(a-b) + a + b) 4/22/2009 10:55:52 AM |