Round-off error in the floating point representation

The IEEE 754 representation has round off errors

  • Most values are not represented exactly     

Example:   0.2(10) = 0.001100110011001100110011...

                          0.2
                     *2 ------- 0
                          0.4
                     *2 ------- 0
                          0.8
                     *2 ------- 1
		          1.6 --> 0.6                 
                     *2 ------- 1
		          1.2 --> 0.2
                     *2 ------- 0
                          0.4
                     *2 ------- 0
                          0.8
                     *2 ------- 1
		          1.6 --> 0.6                 
                     *2 ------- 1
		          1.2 --> 0.2
	                and so on (repeats !)
   

Round-off error in the floating point representation

Note:

  • Round off errors is also found in floating point decimal numbers

    It's in the nature of the representation for fractional values

Example:

    1/7 = 0.14265714265714....    
   

Effect of round-off errors

Consider this Java program: /home/cs255001/demo/java/FloatError.java

public class FloatError
{
   public static void main(String[] arg)
   {
      float f1, f2;

      f1 = 0.2f + 0.2f + 0.2f + 0.2f + 0.2f 
         + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f;    
      f2 = 2.0f;

      if ( f1 == f2 )
      { 
         System.out.println ("f1 == f2");
      }
      else
      { 
         System.out.println ("f1 != f2");
      }
   }
}
   

What will this program print ?

How you should test equality of floating point values in Java

Solution:

public class FloatError
{
   public static void main(String[] arg)
   {
      float f1, f2;

      f1 = 0.2f + 0.2f + 0.2f + 0.2f + 0.2f 
         + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f;    
      f2 = 2.0f;

      if ( Math.abs(f1 - f2) < EPSILON )
      { 
         System.out.println ("f1 == f2");
      }
      else
      { 
         System.out.println ("f1 != f2");
      }
   }
}