Floating point manipulation in Java

Hi All,

Today, I am writing on a very interesting topic “How floating points are handled in java in JAVA?”  Have you ever tried multiplying any two double like:

0.1*0.4

what do you expect the output should be?  0.04? No, that’s not the case, its 0.04000000000000001 crazy 😀

The reason why it is happening is the way double are handled in JAVA. So, to make it easy let us consider above example and understand step by step how double is handled and how JVM managed to give this output.

All floating numbers in Java follow IEEE 754 Double-precision  floating-point format.

According to this standard, out of 64 bits of the binary representation of a floating number,

1st bit is signed bit
Next 11 bits are exponent bits and
Remaining 52 bits are fraction bits

The way we can calculate the corresponding decimal value is :

 

So, let us go to the example we took earlier and try to convert 0.1 to the actual value. The way you can get Binary representation is by executing below piece of code

Double.doubleToRawLongBits(0.1);

which will return below value:

4591870180066957722

And when you convert above decimal value to a binary, it will lead to below number:

0      01111111011      1001100110011001100110011001100110011001100110011010

Now, sign bit here is 0

e is 01111111011 which in decimal format is 1019

and significant bits are 1001100110011001100110011001100110011001100110011010

So,

is

= 1.60000000000000008882

So, putting all these values in the above formula leads to

which is equal to  0.10000000000000000555125

Similarly, if you will convert 0.4 by following above format, it will lead to  0.400000000000000022205

Multiplying these two will lead to 0.04000000000000001 (round of 0.04000000000000000444100000000000012326550625 ) and not just 0.04

This is the reason you can not compare decimal values in java which means 0.4*0.1 is not equal to  0.04

 

Leave a Reply

Your email address will not be published. Required fields are marked *