Python math.isclose() - Check if Two Numbers are Close
Python math.isclose()
math.isclose(a, b) function returns True if a and b are close to each other within given tolerance.
Syntax
The syntax to call isclose() function is
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)where
| Parameter | Required | Description |
|---|---|---|
| a | Yes | A numeric value. |
| b | Yes | A numeric value. |
| * | No | More numeric values. |
| rel_tol | No | Maximum allowed difference between a and b. |
| abs_tol | No | Minimum absolute tolerance. |
Examples
1. Check if 4.1 and 4.2 are close with a tolerance of 0.2
In the following program, we take two numbers: 4.1 and 4.2, and check if these two numbers are close with a tolerance of 0.2.
Python Program
import math
a = 4.1
b = 4.2
result = math.isclose(a, b, abs_tol=0.2)
print('isclose(a, b) :', result)Output
isclose(a, b) : True2. Check if 4.1 and 4.2 are close with a tolerance of 0.05
Now, let us check if these two numbers are close with a tolerance of 0.05.
Python Program
import math
a = 4.1
b = 4.2
result = math.isclose(a, b, abs_tol=0.05)
print('isclose(a, b) :', result)Output
isclose(a, b) : FalseSummary
In this Python Math tutorial, we learned the syntax of, and examples for math.isclose() function.