-1

Why the output of below program is coming out as 5069137140999999500.000000?

public class Add
{
    public static void main (String[] args) throws java.lang.Exception
    {
        double b=5069137140000000000.000000;
        double s=1000000000.000000;
        System.out.printf("%f",(b+s));
    }
}
victini
  • 193
  • 1
  • 6

2 Answers2

0

In Java, double values are IEEE floating point numbers. They cannot be represented exactly, even if they have high precision. That's why some floating point operations will include the round-off error present in these floating point numbers.

It actually doesn't matter what the source of the number is, whether it's parsing a string or specifying a double literal. The problem roots in floating-point representation.

Dimitar
  • 4,402
  • 4
  • 31
  • 47
0

This program demonstrates the following:

The exact value of the sum, 5069137141000000000.0, falls exactly half way between two exactly representable numbers, 5069137140999999500.000000 and 5069137141000000500.000000.

Of those, the lower one, the answer you got, is even and therefore is the correct rounding result.

public class Test {
  public static void main(String[] args) {
    double b=5069137140000000000.000000;
    double s=1000000000.000000;
    System.out.printf("%f%n",(b+s));
    double exact = 5069137141000000000.0;
    System.out.printf("%f%n", exact);
    System.out.printf("%f%n", Math.nextUp(exact));
    System.out.println(Long.toHexString(Double.doubleToLongBits(exact)));
  }
}

Output:

5069137140999999500.000000
5069137140999999500.000000
5069137141000000500.000000
43d1964c57d3c2d4
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75