Compare Floating Numbers

Compare two floating-point numbers with a tolerance to avoid precision issues.

PythonIntermediate
Python
# Program to compare two floating-point numbers

import math

a = float(input("Enter first float: "))
b = float(input("Enter second float: "))
epsilon = 1e-9

if math.isclose(a, b, rel_tol=0.0, abs_tol=epsilon):
    print("Numbers are approximately equal")
elif a > b:
    print("First number is greater")
else:
    print("Second number is greater")

Output

Enter first float: 0.1
Enter second float: 0.1
Numbers are approximately equal

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.