Python cmath - isclose() Function
The Python cmath.isclose() function returns True if the values a and b are close to each other and False otherwise. The two values are considered close using absolute and relative tolerances.
rel_tol is the relative tolerance and it is maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example - to set tolerance of 1%, rel_tol = 0.01 can be used. The default value of rel_tol is 1e-09. rel_tol must be greater than zero.
abs_tol is the minimum absolute tolerance. It is used to compare values near 0. The value must be at least 0. The default value of abs_tol is 0.0.
The result is compared using following formula: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).
NaN, inf, and -inf is handled according to IEEE rules. NaN is not considered close to any other value, including NaN. inf and -inf are considered close to each other.
Syntax
#New in version 3.5 cmath.isclose(a, b, rel_tol, abs_tol)
Parameters
a |
Required. Specify the first value to check value for closeness. |
b |
Required. Specify the second value to check value for closeness. |
rel_tol |
Optional. Specify the relative tolerance. It is maximum allowed difference between a and b. Default value: 1e-09. |
abs_tol |
Optional. Specify the absolute tolerance. It is used to compare values near 0. The value must be at least 0. Default value: 0.0. |
Return Value
Returns True if the values a and b are close to each other, and False otherwise.
Example:
The example below shows the usage of isclose() function.
import cmath print(cmath.isclose(100 + 2j, 104 + 2j)) print(cmath.isclose(100 + 3j, 104 + 3j, rel_tol = 0.05)) print(cmath.isclose(100j, 100.0000000001j)) print(cmath.isclose(3+ 100j, 3+ 101j, abs_tol = 2))
The output of the above code will be:
False True True True
❮ Python cMath Module