Clamping floating numbers in Python? [duplicate]
Asked Answered
H

3

38

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

Something like:

clamp(myValue, min, max)
Halophyte answered 19/3, 2012 at 18:25 Comment(0)
U
60

There's no such function, but

max(min(my_value, max_value), min_value)

will do the trick.

Underhill answered 19/3, 2012 at 18:26 Comment(1)
I always like to order it like, min(max(low, value), high). And think of it like low < value < high. Then it also reads like a "min-max" function minmax(low, value, high)Clausen
U
64

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
Urena answered 5/11, 2012 at 12:41 Comment(2)
This seems to be extremely slow, though. I'm guessing it's because this function was meant for arrays.Ary
@Micael: Numpy is always meant for arrays, where it works faster for than any pure-Python alternative. If a person is worrying about the speed of pure-Python it's usually an indication they need to redesign to use arrays, offload, or switch languages.Urena
U
60

There's no such function, but

max(min(my_value, max_value), min_value)

will do the trick.

Underhill answered 19/3, 2012 at 18:26 Comment(1)
I always like to order it like, min(max(low, value), high). And think of it like low < value < high. Then it also reads like a "min-max" function minmax(low, value, high)Clausen
I
12

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).

Incognizant answered 20/10, 2019 at 5:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.