Reference articles on history, science, culture and more
Encyclopedia

Clamp (function)

Limiting a position to an area

In computer science, clamping, or clipping is the process of limiting a value to a range between a minimum and a maximum value. Unlike wrapping, Clamping moves a value to the nearest boundary if it is outside the allowed range.

Y = clamp(X, 1, 3)
XY
01
11
22
33
43

In Python, clamping can be defined as follows:

def clamp(x, minimum, maximum): if x < minimum: return minimum if x > maximum: return maximum return x

This is equivalent to max(minimum, min(x, maximum)) for languages that support the functions min and max.

01Uses

One of the many uses of clamping in computer graphics is the placing of a detail inside a polygon, for example, a bullet hole on a wall. It can also be used with wrapping to create a variety of effects.

02Implementations

Several programming languages and libraries provide functions for fast and vectorized clamping. In Python, the pandas library offers the Series.clip and DataFrame.clip methods. The NumPy library offers the clip function. In the Wolfram Language, it is implemented as Clip[x, {minimum, maximum}].

In OpenGL, the glClearColor function takes four GLfloat values which are then clamped to the range [0,1].

In CSS, clamp() can help to implement responsive typography or responsive designs generally.

Although spreadsheets like Excel, Open Office Calc, or Google Sheets don't provide a clamping function directly, the same effect can be achieved by using functions like MAX and MIN together, by MEDIAN, or with cell function macros. When attempting to do a clamp where the input is an array, other methods must be used.

Watch videos about Clamp (function)Explainers and documentaries on YouTube (opens in a new tab)

Sources and credits

This article is adapted from the Wikipedia article Clamp (function), written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.

Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.