/** * Equality check of floating-point numbers */ public class FPNumbersEqual { public static void main(String[] args) { float x = 1.0f - 0.1f - 0.1f - 0.1f - 0.1f - 0.1f; System.out.println("x = " + x); System.out.println("x == 0.5 = " + (x == 0.5f)); double y = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1; System.out.println("y = " + y); System.out.println("y == 0.5 = " + (y == 0.5)); // The textbook recommends using an epsilon of 1e-7 for comparing floats // and 1e-14 for comparing doubles double epsilon = 1e-7; System.out.println("x == 0.5 = " + (Math.abs(x - 0.5f) < epsilon)); epsilon = 1e-14; System.out.println("y == 0.5 = " + (Math.abs(y - 0.5) < epsilon)); } }