
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clamp Floating Numbers in Python
Clamping refers to limiting a number to a specific range, i.e., making sure that the number lies between the minimum and maximum value mentioned. This method is used in applications like graphics and statistical computations, as it requires the data to stick to specific limits.
Clamping Floating Numbers in Python
The following are some of the approaches to clamp floating numbers in Python -
Creating a User-Defined Function
Since Python has no built-in clamp function, in the following program, we will create our clamp() function, which takes three parameters - n (number to be clamped), min (minimum value), and max (maximum value) -
def clamp(n, min, max): if n < min: return min elif n > max: return max else: return n print(clamp(7.5, 5.0, 20.0)) print(clamp(-1.23, 11.0, 20.0)) print(clamp(15.44, 9.0, 12.0))
The above code returns the number if it is already within the mentioned range, min if n is less than min, and max if n is more than max. Following is the output -
7.5 11.0 12.0
Using Numpy Inbuilt Method
In the following program by using the Numpy inbuilt method, we will use the numpy.clip() function to clamp floating numbers in Python. The numpy.clip() function is a built-in function that clips the values in an array, i.e., values outside the interval are clamped to the interval edges.
import numpy as np clamped_number = np.clip(7.5, 5.0, 20.0) print(clamped_number) clamped_number = np.clip(-3.4, 0.0, 5.7) print(clamped_number) clamped_number = np.clip(6.89, 0.0, 5.7) print(clamped_number)
Following is the output for the above code -
7.5 0.0 5.7
Using PyTorch Inbuilt Method
In the following program, we will use the built-in method in Pytorch, i.e., torch.clamp(), to clamp the floating numbers in Python. The torch.clamp() method is used to clamp all the elements in the input into the range [min, max].
import torch num = torch.tensor(7.5) num = torch.clamp(num, min=5.3, max=20.5) print(num.numpy())
The output for the above code is as follows -
7.5