0

Why does this equation produce two different values for e in C (32-bit) and Java (64-bit)? They are off by an unexpectedly large amount.

int a, b, c, d;
double e;

a = -12806;
b = 1;
c = 800;
d = 19209;

double f = (32768 / 10.24);

e = (a + (double) b / c * d) / f;

C produces -3.9940624237060547. Java produces -3.9943714843750002.

UPDATE:

Sorry folks, this error appears to be something else than I expected. I reduced my code to just this equation and the numbers it produces are much closer.

mark
  • 1,398
  • 13
  • 30

2 Answers2

1

In Java the implicit braces are a bit different:

    int a, b, c, d;
    double e;

    a = 3;
    b = 4;
    c = 5;
    d = 6;
    e = a + (double) b / c * d;
    System.out.println("e=" + e);
    e = a + (((double) b) / c) * d; // Java: 7.8
    System.out.println("e=" + e);

If you run this in C you will see the difference.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

This has been answered here:

Retain precision with double in Java

Your best bet would be to use BigDecimals as these retain this precision.

Community
  • 1
  • 1