0

I want to ask, because this cycle throws me false ?, not know why that is the result. I think it has to do with floating point

Thank you for your help.

double a = 2d;
System.out.println(a);

double b = 2.6d ;
System.out.println(b);

for (int i = 0; i < 6 ; i ++)
{
    a+= 0.1;
}

System.out.println ( a==b ) ;

RUN

2.0
2.6
false
  • Use the debugger of your IDE to see exactly what's happening. You will notice how the lack of precision creeps in. I tested your particular code to see the value of `a` rise as follows: 2.0, 2.1, 2.2, 2.3000000000000003, ... – Chthonic Project Sep 28 '14 at 03:37

1 Answers1

1

You get false because you are checking two doubles for equality. In theory, the two values should be equal. However, double representation of 0.1 is inexact, so adding it six times to 2.0 does not result in precisely the value of 2.6. There is a small difference, which results in your comparison failing.

Change the last line to this:

System.out.println ( Math.abs(a-b) ) ;

to see how small is the magnitude of the error (it is roughly 4.44*10-16 (demo)).

If you would like to perform precise operations on decimal values Java, use BigDecimal type instead of `double.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523