C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Compare Two floats precisely (Epsilon-Based)

Why Epsilon Comparison?

Floating-point numbers may not be stored exactly in memory, so direct comparison using == can give incorrect results.
An epsilon-based comparison checks whether the difference between two numbers is small enough to be considered equal.

import java.util.Scanner;

 

public class FloatComparison {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter first floating-point number: ");

        double num1 = sc.nextDouble();

 

        System.out.print("Enter second floating-point number: ");

        double num2 = sc.nextDouble();

 

        // Define tolerance (epsilon)

        double epsilon = 0.000001;

 

        System.out.println("\n------ Float Comparison Result ------");

 

        if (Math.abs(num1 - num2) < epsilon) {

            System.out.println("Both numbers are approximately equal.");

        }

        else if (num1 > num2) {

            System.out.println("First number is greater than second number.");

        }

        else {

            System.out.println("Second number is greater than first number.");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1:

INPUT : 
Enter first floating-point number: 0.3
Enter second floating-point number: 0.3000001

OUTPUT :
------ Float Comparison Result ------
Both numbers are approximately equal.

OUTPUT 2:
 
INPUT : 
Enter first floating-point number: 5.25
Enter second floating-point number: 5.10

OUTPUT :
------ Float Comparison Result ------
First number is greater than second number.

OUTPUT 3:
 
INPUT : 
Enter first floating-point number: 4.75
Enter second floating-point number: 4.90

OUTPUT :
------ Float Comparison Result ------
Second number is greater than first number.

Explanation

1. Input Two Floating-Point Numbers

double num1 = sc.nextDouble();

double num2 = sc.nextDouble();

  • Reads two decimal numbers from the user.

2. Epsilon Definition

double epsilon = 0.000001;

  • Represents the allowed tolerance for comparison.

3. Epsilon-Based Comparison

Math.abs(num1 - num2) < epsilon

  • Calculates the absolute difference between the two numbers.
  • If the difference is smaller than epsilon, they are treated as equal.

4. Logical Decision

if (...)

else if (...)

else

  • Determines equality, greater-than, or less-than.