.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 betweena
andb
. 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 betweena
andb
. 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()
area
andb
; 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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours