Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001.
- * Note that we cannot directly compare two floating-point numbers a and b by a==b because of the nature
- * of the floating-point arithmetic. Therefore, we assume two numbers are equal
- * if they are more closely to each other than a fixed constant eps. */
- import java.util.Locale;
- import java.util.Scanner;
- public class ComparingFloats {
- private static final double eps = 0.000001;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Locale.setDefault(Locale.ROOT);
- System.out.print("Enter your First real number, numA = ");
- Scanner reader = new Scanner(System.in);
- double numA = reader.nextDouble();
- System.out.print("Enter another real number, numB = ");
- double numB = reader.nextDouble();
- double diff = Math.abs(numA - numB);
- boolean numsIsEquals = diff < eps;
- System.out.printf("The First number is Equal on Second number: %b!\n", numsIsEquals);
- reader.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement