Compare Floating Numbers in Python
Compare two floating-point numbers with a tolerance to avoid precision issues.
IntermediateConditional ProgramsExample 15 of 20
compare-floating-numbers.py
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
Enter first float: 0.1 Enter second float: 0.1 Numbers are approximately equal
What's going on
Due to floating-point precision, direct equality checks can be unreliable.
We use math.isclose() with a small absolute tolerance to decide equality before comparing magnitude.
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.