• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #6: Double Arithmetic

Contents

  • Java Puzzle #6: Double Arithmetic
    • Solution
    • Explanation
    • Resolve problem

What is the output of the following snippet?

public class test {
    public static void main(String[] args) {
        double a = 1.3378901234567877;
        double b = 0.0008901234567876;
        double c = a - b;

        if (c == 1.337) {
            System.out.println("Hallo doubles!");
        } else {
            System.out.println("Oh no! Comparison failed!");
        }
    }
}

. . . . . . . . . . . . . . . . .

Solution

Oh no! Comparison failed!

Explanation

Doubles are internally represented using the IEEE 754 standard (source). This means, doubles are not represented with arbitrary precision.

Just execute this snippet:

public class test {
    public static void main(String[] args) {
        double a = 1.3378901234567876;
        System.out.println("a = " + a);
        double b = 0.0008901234567876;
        System.out.println("b = " + b);
        double c = a - b;
        System.out.println("c = " + c);
    }
}

Output:

a = 1.3378901234567877
b = 8.901234567876E-4
c = 1.3370000000000002

Resolve problem

Use an appropriate epsilon to compare floats/doubles:

public class test {
    public static void main(String[] args) {
        double a       = 1.3378901234567877;
        double b       = 0.0008901234567876;
        double c       = a - b;
        double EPSILON = 0.000000000000001;

        if (Math.abs(c - 1.337) < EPSILON) {
            System.out.println("Hallo doubles!");
        } else {
            System.out.println("Oh no! Comparison failed!");
        }
    }
}

Published

Aug 4, 2012
by Martin Thoma

Category

Code

Tags

  • Java 36
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor