# ENIGMA Forums

## Contributing to ENIGMA => Function Peer Review => Topic started by: RetroX on December 13, 2010, 04:15:09 PM

Title: clamp()
Post by: RetroX on December 13, 2010, 04:15:09 PM
Code: [Select]
`double clamp(double x, double lower, double upper) { return (x < lower ? lower : (x > upper ? upper : x)); }`
Simple function that would be useful.
Title: Re: clamp()
Post by: Fede-lasse on December 14, 2010, 04:09:23 AM
What does it do?
Title: Re: clamp()
Post by: serprex on December 14, 2010, 09:02:45 AM
Get out your minmax, let's go out tonight, it'll be a bang and the whole gang'll rival up on in with the llllllllllittle cherries and sweeeeeeeeeeet comparies. So get out your min(max(x,lower),upper) tonight
Title: Re: clamp()
Post by: Fede-lasse on December 14, 2010, 10:40:30 AM
You mean median()?
Title: Re: clamp()
Post by: TheExDeus on December 14, 2010, 11:14:51 AM
Quote
You mean median()?
No he means clamp(). There is no equivalent in GM. It returns "lowest" when x<lowest, and highest when x>highest, and x when its between the two. Dunno if serpex's method is better thou. Because using at most two if cycles could be better than using always two function calls.
Title: Re: clamp()
Post by: polygone on December 14, 2010, 12:20:05 PM
That's what median does in GML.
Title: Re: clamp()
Post by: IsmAvatar on December 14, 2010, 12:58:26 PM
Median works in its place on a technicality.

Consider three cases.
1) X < L < H
2) L < X < H
3) L < H < X

in each of these three cases, median picks the middle number. If X < L, median picks L since L happens to be in the middle. If X > H, median picks H since H happens to be in the middle. If L<X<H, median picks X.

However newbies aren't privy to this fact, since the name isn't exactly self explanatory, and it's not normally documented for this purpose. Having a clamp that simply delegates to median would work fine.
Title: Re: clamp()
Post by: TheExDeus on December 14, 2010, 01:38:34 PM
Thanks. Didn't know that. I did use median for a different purpose, and having up to 16 arguments (in GML) didn't help me get the idea either.
Title: Re: clamp()
Post by: IsmAvatar on December 14, 2010, 05:54:39 PM
Another neat thing about median is that argument order doesn't matter.
Title: Re: clamp()
Post by: RetroX on December 14, 2010, 07:34:40 PM
eh I really wasn't paying attention when I wrote this

But yeah, median works. :V  So does minmax.
Title: Re: clamp()
Post by: Josh @ Dreamland on December 14, 2010, 07:56:34 PM
Clamp is more efficient than median, unless median is specialized for each argument count.
Title: Re: clamp()
Post by: RetroX on December 16, 2010, 03:37:13 PM
Clamp is more efficient than median, unless median is specialized for each argument count.
Which is why min(max(x,min),max) is the best