How to use the math.isclose() function in Python?
The math module in Python contains a number of mathematical operations, which can be performed very easily and make our lives a lot simpler. Amongst some of the most important functions in this module, is the isclose() function.
The math.isclose() function is used to check whether two given values are close to each other. The closeness of the two values is determined according to the given absolute and relative tolerances. The function returns
True, if the values are close.False, if they are not close.
Syntax
math.isclose(a, b, rel_tol, abs_tol)
Parameters
a: It is a required parameter and signifies the first value to check for closeness.b: It is a required parameter and signifies the second value to check for closeness.rel_tol= value: It is an optional parameter and determines the relative tolerance between a and b. It has a default value of 1e-09.abs_tol= value: It is an optional parameter and determines the minimum absolute tolerance. The value must be at least 0.
import mathprint(math.isclose(8.005, 8.450, abs_tol = 0.4))print(math.isclose(8.005, 8.450, abs_tol = 0.5))
Explanation
-
In line 1, we imported the
mathmodule in Python. -
In lines 2 and 3, we use the
math.isclose()function to compare the two values. -
The first output is false. This is because the two given numbers have an absolute difference of 0.445, while the threshold mentioned is 0.4.
-
The second output is true. This is because the two given numbers have an absolute difference of 0.445, while the threshold mentioned is 0.5.