Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to clamp floating numbers in Python?
Clamping refers to limiting a number to a specific range, ensuring that the number lies between the minimum and maximum values. This method is used in applications like graphics and statistical computations, as it requires data to stick to specific limits.
Creating a User-Defined Function
Since Python has no built-in clamp function, we can create our own clamp() function that takes three parameters − n (number to be clamped), min_val (minimum value), and max_val (maximum value) ?
def clamp(n, min_val, max_val):
if n < min_val:
return min_val
elif n > max_val:
return max_val
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 range, min_val if n is less than min_val, and max_val if n is greater than max_val ?
7.5 11.0 12.0
Using NumPy clip() Method
NumPy provides a built-in numpy.clip() function that clips values in an array. 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)
The output shows the clamped values ?
7.5 0.0 5.7
Using PyTorch clamp() Method
PyTorch provides torch.clamp() method to clamp all elements in a tensor within the range [min, max] ?
import torch num = torch.tensor(7.5) num = torch.clamp(num, min=5.3, max=20.5) print(num.item())
The output for the above code is ?
7.5
Comparison of Methods
| Method | Pros | Cons | Best For |
|---|---|---|---|
| Custom Function | No dependencies | Must implement yourself | Simple projects |
| NumPy clip() | Vectorized, efficient | Requires NumPy | Array operations |
| PyTorch clamp() | GPU support | Requires PyTorch | Deep learning projects |
Conclusion
Use a custom function for simple clamping without dependencies. Choose NumPy's clip() for array operations or PyTorch's clamp() for tensor-based computations.
