Python .isclose()
Published Jul 25, 2024
Contribute to Docs
The .isclose() function returns True when two floating-point numbers are close to each other within a specified tolerance. This is useful when comparing a value to an expected value, without requiring exact equality. For example, the comparison 0.1 + 0.2 == 0.3 returns False, but using .isclose() would return True.
Syntax
math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0)
a: The first float value to be compared.b: The second float value to be compared.rel_tol: Relative tolerance is the maximum allowed relative difference betweenaandb. The default value is1e-09, which means the values are considered close if their relative difference is within 9 decimal places. The tolerance value must be greater than zero.abs_tol: Absolute tolerance is the minimum absolute difference allowed betweenaandb. The default value is0.0, which means no absolute tolerance is applied. This parameter can be set to any non-negative number. Absolute tolerance is particularly useful for comparisons involving values near zero.
Note: The required parameters for
.isclose()areaandb; all other parameters are optional.
Example
Here is an example of .isclose():
import mathx = 0.1y = 0.2print(math.isclose(x + y, 0.3))print(math.isclose(x + y, 0.3, rel_tol=0.01))print(math.isclose(x + y, 0.3, rel_tol=1e-20))print(math.isclose(x + y, 0.3, abs_tol=0.01))print(math.isclose(x + y, 0.4, abs_tol=0.01))
The above code gives the following output:
TrueTrueFalseTrueFalse
Codebyte Example
Run the following code to understand how the .isclose() function works:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours