Open In App

How to clamp floating numbers in Python

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.






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.






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.




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

Output:

25

Conclusion


Article Tags :