In this tutorial, we will explore how to set upper and lower bounds in Python to limit the range of values a variable can take. Setting bounds is essential when working with functions, optimization problems, or designing algorithms.
Step 1: Setting Bounds using Min and Max Functions
Python provides built-in functions, min() and max(), to set bounds on numeric data types like integers and floats. These functions can be used to easily set upper or lower bounds to a variable when working with numbers.
Here’s an example of using the min() and max() functions:
1 2 3 4 5 6 |
value = 25 lower_bound = 10 upper_bound = 50 bounded_value = max(min(value, upper_bound), lower_bound) print("Bounded Value:", bounded_value) |
In this example, the value is set to 25, and we want to ensure it remains within the bounds of 10 to 50. If we change the value to 5 or 55, it will still be assigned the lower or upper bound.
Output:
Bounded Value: 25
Step 2: Setting Bounds using Numpy Clip Function
Another approach to set bounds in Python is by using the clip() function from the Numpy library. This method is particularly useful when working with arrays or matrices. As compared to the min() and max() functions, clip() makes it more convenient to set upper and lower bounds for all elements in an array.
First, install the Numpy library using the following command:
1 |
pip install numpy |
Now, let’s see an example of using Numpy’s clip() function:
1 2 3 4 5 6 7 8 |
import numpy as np values = np.array([5, 15, 25, 35, 45, 55]) lower_bound = 10 upper_bound = 50 bounded_values = np.clip(values, lower_bound, upper_bound) print("Bounded Values:", bounded_values) |
Output:
Bounded Values: [10 15 25 35 45 50]
This example shows how the clip() function can be used to set bounds on an array. The input array has values outside the given range, and the output array contains values within the specified bounds.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import numpy as np # Using min() and max() functions value = 25 lower_bound = 10 upper_bound = 50 bounded_value = max(min(value, upper_bound), lower_bound) print("Bounded Value:", bounded_value) # Using Numpy's clip() function values = np.array([5, 15, 25, 35, 45, 55]) lower_bound = 10 upper_bound = 50 bounded_values = np.clip(values, lower_bound, upper_bound) print("Bounded Values:", bounded_values) |
Conclusion
In this tutorial, we learned how to set upper and lower bounds in Python using built-in functions, min() and max(), and the clip() function from the Numpy library. These methods are useful when working with functions, optimization problems, or designing algorithms.