Open In App

How to clamp floating numbers in Python

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Clamping is a method in which we limit a number in a range or in between two given numbers. When we clamped a number then it holds the value between the given range. If our clamped number is lower than the minimum value then it holds the lower value and if our number is higher than the maximum value then it holds the higher value. Python doesn’t have any function to do the clamping of a number. We need to create our own user-built function to do so.

Example 1:
Input: 5
Range: [1, 10]
Output: 5

Example 2:
Input: 5
Range: [10, 20]
Output: 10

Example 3:
Input: 10
Range: [1, 5]
Output: 5

Creating user-defined function

Now let’s implement a clamp(n, min, max) method which takes three parameters where n is the number we would like to clip and the range to be used for clipping the number.

Python3




def clamp(n, min, max):
    if n < min:
        return min
    elif n > max:
        return max
    else:
        return n
  
print(clamp(5, 1, 20))
print(clamp(1, 15, 20))
print(clamp(15, 1, 12))


Output:

5
15
12

Using the Numpy Inbuilt Method

In Numpy as we have a clip method to do clamping of a number.

Python3




import numpy as np
print(np.clip(10, 6, 20))


Output:

10

Using the PyTorch Inbuilt Method

In PyTorch as we have a clamp method to do clamping of a number.

Python3




import torch
  
num = torch.tensor(135)
num = torch.clamp(num, min=10,
                  max=25)
print(num.numpy())


Output:

25

Conclusion

  • If the number is in between the range it will hold the value as it is
  • If the number is lower than the minimum value of the range then it will hold the minimum range value
  • If the number is greater than the maximum value of the range then it will hold the maximum range value


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads