Compare Floating Numbers

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

IntermediateTopic: Conditional Programs
Back

Python Compare Floating Numbers Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding Compare Floating Numbers

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.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents