Python math.isclose() Method
The math.isclose() method in Python returns True if the two values are close to each other, otherwise it returns False.
math.isclose() determines whether two values are considered close based on given absolute and relative tolerances.
Python version: 3.5
The formula used for calculation is:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
Syntax
The syntax for the math.isclose() method is as follows:
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Parameter Description:
a -- Required, a number. Returns TypeError if a is not a number. Returns ValueError if the value is zero or negative.
b -- Required, a number. Returns TypeError if b is not a number. Returns ValueError if the value is zero or negative.
rel_tol -- The relative tolerance, which is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, ensuring that the two values are the same within approximately 9 decimal places. rel_tol must be greater than zero.
abstol -- The minimum absolute tolerance, useful for comparisons near zero. abstol must be at least zero.
Return Value
Returns a Boolean value, checking whether the two values are close to each other. Returns True if the values are close, otherwise returns False.
Example
The following example checks if two values are close to each other:
# Import math package
import math
# Output whether the two values are close
print(math.isclose(8.005, 8.450, abs_tol=0.4))
print(math.isclose(8.005, 8.450, abs_tol=0.5))
Output result:
False
True
The following example checks if two floating-point numbers are close:
# Import math package
import math
# Useful for floating-point comparisons
# This will output false, as 0.1+0.2 does not equal 0.3
print(0.1+0.2 == 0.3)
print(0.1+0.2)
# This will output true
print(math.isclose(0.1+0.2, 0.3))
Output result:
False
0.30000000000000004
True