0

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
Murtaza Zaidi
  • 599
  • 3
  • 14
  • Precisions are doubled when you use `double`. You are sacrificing precision when doing the save with float. You should get a compile warning saying that b's precision might be lost or something. Also check out the IEEE floating point number specification when using programming languages and how they are represented. – ha9u63a7 Nov 09 '14 at 18:26

1 Answers1

2

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.

DevOps85
  • 6,473
  • 6
  • 23
  • 42