Floating point operators and associativity in Java

Java Programming Java 8Object Oriented Programming

Following programs shows the float arithmetic can cause dubious result if integer values are used using float variables.

Example

public class Tester {
   public static void main(String[] args) {

      float a = 500000000;
      float b = -500000000;
      float c = 1;
      float sumabc1 = a+(b+c);
      float sumabc2 =(a+b)+c;

      System.out.println("Floating Point Arithmetic");
      System.out.println("a + ( b + c ) : " + sumabc1);
      System.out.println("(a + b) + c : " + sumabc2);

      float sumbc = b + c;
      float sumab = a + b;

      System.out.println("b + c : " + sumbc);
      System.out.println("a + b : " + sumab);

      int a1 = 500000000;
      int b1 = -500000000;
      int c1 = 1;

      int sumabc11 = a1+(b1+c1);
      int sumabc21 =(a1+b1)+c1;

      System.out.println("Integer Arithmetic");
      System.out.println("a + ( b + c ) : " + sumabc11);
      System.out.println("(a + b) + c : " + sumabc21);

      int sumbc1 = b1 + c1;
      int sumab1 = a1 + b1;

      System.out.println("b + c : " + sumbc1);
      System.out.println("a + b : " + sumab1);
   }
}

Output

Floating Point Arithmetic
a + ( b + c ) : 0.0
(a + b) + c : 1.0
b + c : -5.0E8
a + b : 0.0
Integer Arithmetic
a + ( b + c ) : 1
(a + b) + c : 1
b + c : -499999999
a + b : 0

Here you can see that a + ( b + c ) is not same as (a + b) + c in float arithmetic.

The reason behind the same is the rounding off of the result because of floating point arithmetic. b + c results in -500000000 instead of -499999999 whereas the same in integer arithmetic yield the desired result.

raja
Published on 14-Aug-2018 10:53:06
Advertisements