Clamping floating numbers in Python?
Question:
Is there a built-in function for this in Python 2.6?
Something like:
clamp(myValue, min, max)
Answers:
There’s no such function, but
max(min(my_value, max_value), min_value)
will do the trick.
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
I think the question is answered but here’s an alternative DIY solution if anyone needs it:
def clip(value, lower, upper):
return lower if value < lower else upper if value > upper else value
(Slightly faster than @Sven Marnach’s answer – even when in bounds).
Is there a built-in function for this in Python 2.6?
Something like:
clamp(myValue, min, max)
There’s no such function, but
max(min(my_value, max_value), min_value)
will do the trick.
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
I think the question is answered but here’s an alternative DIY solution if anyone needs it:
def clip(value, lower, upper):
return lower if value < lower else upper if value > upper else value
(Slightly faster than @Sven Marnach’s answer – even when in bounds).