Compare Floating Numbers in Python
Choose what close means before comparing Python floats. A beginner math.isclose example uses an absolute tolerance and separates approximate equality from order.
1# Program to compare two floating-point numbers23import math45a = float(input("Enter first float: "))6b = float(input("Enter second float: "))7epsilon = 1e-989if math.isclose(a, b, rel_tol=0.0, abs_tol=epsilon):10 print("Numbers are approximately equal")11elif a > b:12 print("First number is greater")13else:14 print("Second number is greater")
Output
Numbers are approximately equal
Both entered values are 0.1, so the closeness test succeeds.
In this one
- Choose an absolute tolerance
- Call math.isclose before ordering
- Distinguish representation error from input validation
How it works
- 1
Read a and b as floats and set epsilon.
- 2
Call isclose with rel_tol zero and abs_tol epsilon.
- 3
If not close, compare a > b and print which value is larger.
Edge cases
Near zero
Compare 0 with 0.0000000005.
The difference is below 1e-9, so they count as approximately equal.
Different scale
Compare very large nearby measurements.
The fixed absolute tolerance may be inappropriate; choose a policy for the data.
What's going on
Some decimal fractions cannot be stored exactly as binary floats. A calculation such as 0.1 + 0.2 can therefore differ slightly from 0.3. That does not mean all float equality is broken; it means the intended comparison needs a policy.
This code chooses an absolute tolerance of 1e-9 and disables relative tolerance with rel_tol=0.0. math.isclose checks whether the finite values differ by at most that fixed amount. If they are close, the code reports approximate equality before comparing greater-than.
The identical 0.1 sample is close even with exact equality; try nearby values to see the tolerance matter. A fixed tolerance suits a fixed measurement scale but may be too strict for huge magnitudes. nan is not close to anything and would make this final else misleading, so the lesson assumes finite inputs.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does abs_tol=1e-9 mean here?
Pick an answer to check it.
Question 2
Why set rel_tol to zero?
Pick an answer to check it.
Questions people ask
What does abs_tol=1e-9 mean here?
For finite values, a difference up to 0.000000001 is accepted as close.
Why set rel_tol to zero?
It disables scale-relative tolerance so this example uses only the stated absolute margin.
Does isclose repair the stored floats?
No. It returns a Boolean judgment; it does not change either input.