views:

384

answers:

7

I find that I frequently end up writing a function that I always call "clamp()", that is kind of a combination of min() and max(). Is there a standard, "canonical" name for this function?

It always looks something like this:

function clamp($val, $min, $max)
{
  if ($val < $min)
    return $min;
  else if ($val > $max)
    return $max;
  else
    return $val;
}

Or simply using built-in min() and max() functions:

function clamp($val, $min, $max)
{
  return max($min, min($max, $val));
}

Variations exist: You can also check for invalid input, where min > max, and either throw an exception or reverse the inputs. Or you can ignore order of the inputs and call it a median-of-three function, but that can be confusing.

A: 

I'd just go for a function name "rangeCheck"

tehvan
not good, rangeCheck sounds like it CHECKS. But what it does is CHANGING values to be in a range.
Thorsten79
+22  A: 

clamp is a good name.

Let us make it the standard.

Niyaz
Seems to be standard (at least in graphics) already: http://en.wikipedia.org/wiki/Clamping_%28graphics%29
Zach Scrivena
Hmm.. maybe I picked "clamp" up at some point and forgot where i got it from..
Kip
Kind of a great name after I understood what it was. Plus one to the standard.
Rodrigo
I think "clip" is more commonly used.
John D. Cook
Numbers may be clamped, while images may be clipped.
Justice
A: 

In the C++ STL, we have std::numerical_limits<type>, which provides both a min() and a max() function. (And some more.)

xtofl
+4  A: 

In some languages you have the function limit

num = limit(val, min, max)

Jim C
+1  A: 
clip(val, lo, hi)
J.F. Sebastian
A: 

median

Because it generalizes to more values.

Strilanc
This isn't about finding statistical information about a sample set. It's about forcing a number to be in a particular range.
MSN
@MSN: technically median(val, min, max) will do the same thing as clamp(val, min, max). plus, the order of the parameters to median() wouldn't matter. but that's not immediately obvious (at least, it wasn't to me).
Kip
Median has the advantage of being self descriptive. You get the median element back.For example, will "clamp" throw an exception if my min is less than my max? In that case, which argument is the min? First or second? These details might change from place to place.
Strilanc
I must disagree with median being self descriptive, since we don't want the median of a given set of values, but clamp a given value to some boundaries. While that may be the same operation internally (well not exactly, but close enough), the purpose of that median call wouldn't be as clear as for example clamp, so it gets harder for other people to read the code.
Grizzly
+1  A: 

We use pin here. Actually, we use pin for simple ranges and clamp for other stuff.

MSN