Search code examples
javadoublefloating-point-precision

Inaccurate calculations using double and float


Why this piece of code is giving inaccurate results?

double a = 0.3 + 0.3 + 0.3;
System.out.println(a);
float b = 0.3f + 0.3f + 0.3f;
System.out.println(b);

Results are

0.8999999999999999
0.90000004

Solution

  • In Java, double values are IEEE floating point numbers. Unless they are a power of 2 (or sums of powers of 2, e.g. 1/8 + 1/4 = 3/8), they cannot be represented exactly, even if they have high precision. Some floating point operations will compound the round-off error present in these floating point numbers. In cases you've described above, the floating-point errors have become significant enough to show up in the output.