How to clamp floating numbers in Python
Hello, Coders!! In this Python tutorial, we will learn to clamp or clip the floating-point numbers in a Python program.
Concept of Clamping a number
The clamp is a method to limit a number between two numbers. When a number is clamped, it keeps its value if it is in between the given range. If it is lower than the min value, it takes the lower value or if it is higher than the max value, then it takes the higher value.
Example:
Let’s take a number 5 and the range is min:0 and max:3. If we clamp the number 5 we will get the value 3 as the number 5 is initially higher than the max range and not lower than the min value.
Let’s explore the methods to clamp floating numbers through example programs:
Clamping floating numbers using a user-defined function in Python
There is no such built-in function for clamping in Python. We can define the function for clamping as follows:
def clamp(num, min, max): return min if num < min else max if num > max else num
Example:
def clamp(num, min, max): return min if num < min else max if num > max else num print(clamp(0.5, 1, 3)) print(clamp(0.23, 0.15, 0.31)) print(clamp(1.35, 0.10, 0.25))
Output:
1 0.23 0.25
Clamping floating numbers using numpy.clip() method
We can also clamp numbers using the NumPy’s clip() method.
Syntax:
numpy.clip(num,min,max)
Example:
import numpy numpy.clip(2.5, 1, 3)
Output:
2.5
numpy.clip(0.23, 0.15, 0.31)
Output:
0.23
Clamping floating numbers using PyTorch clamp() method
Using PyTorch library’s torch.clamp() method we can clamp the input element in the given range.
Syntax:
torch.clamp(num,min,max,out=None) #out:Output Tensor
Example:
import torch print(ex1 = torch.clamp(0.1, min = 1, max = 3)) print(ex2 = torch.clamp(0.23, min = 0.15, max = 0.31)) print(ex3 = torch.clamp(1.35, min = 0.10, max = 0.25))
Output:
1 0.23 0.25
Hope you have enjoyed this article and learned how we can clamp floating numbers in a Python program using various methods.
Happy Coding!!
You can also read, DataType objects in NumPy Python
Leave a Reply