Clamping floating numbers in Python?

Joan Venge picture Joan Venge · Mar 19, 2012 · Viewed 40.9k times · Source

Is there a built-in function for this in Python 2.6?

Something like:

clamp(myValue, min, max)

Answer

Richard picture Richard · Nov 5, 2012

Numpy's clip function will do this.

>>> import numpy
>>> numpy.clip(10,0,3)
3
>>> numpy.clip(-4,0,3)
0
>>> numpy.clip(2,0,3)
2