Clamping floating numbers in Python?

ぐ巨炮叔叔 提交于 2019-11-30 00:20:06

问题


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

Something like:

clamp(myValue, min, max)

回答1:


There's no such function, but

max(min(my_value, max_value), min_value)

will do the trick.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/9775731/clamping-floating-numbers-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!