Advertisement
dimipan80

Comparing Floats

Aug 3rd, 2014
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. /* Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001.
  2.  * Note that we cannot directly compare two floating-point numbers a and b by a==b because of the nature
  3.  * of the floating-point arithmetic. Therefore, we assume two numbers are equal
  4.  * if they are more closely to each other than a fixed constant eps. */
  5.  
  6. import java.util.Locale;
  7. import java.util.Scanner;
  8.  
  9. public class ComparingFloats {
  10.     private static final double eps = 0.000001;
  11.  
  12.     public static void main(String[] args) {
  13.         // TODO Auto-generated method stub
  14.         Locale.setDefault(Locale.ROOT);
  15.         System.out.print("Enter your First real number, numA = ");
  16.         Scanner reader = new Scanner(System.in);
  17.         double numA = reader.nextDouble();
  18.         System.out.print("Enter another real number, numB = ");
  19.         double numB = reader.nextDouble();
  20.         double diff = Math.abs(numA - numB);
  21.         boolean numsIsEquals = diff < eps;
  22.  
  23.         System.out.printf("The First number is Equal on Second number: %b!\n", numsIsEquals);
  24.         reader.close();
  25.     }
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement