Python – Clamp

Released

Here is a quick little trick – How to be sure that a value is between a minimum and a maximum? Say you have an algorithm that requires values between some arbitrary set of numbers, like -10.5 and 15.99. This function will clamp a number between your given boundaries, or clip it at those markers. Not particularly fancy but it’s still a handy little utility function to have around.

def clamp(this_number, minimum, maximum):
''' Insures that your number is between the given min and max values.  Clamps or Clips the number.
        **********ARGUMENTS**********
        :param this_number: input values - incoming data should be standardized
        :param minimum: lower boundry, min value
        :param maximum: upper boundry, max value
        **********RETURNS**********
        :return: minimum if min >= this_number;  maximum if  max <= this_number
        '''
    return max(minimum, min(this_number, maximum))