Floating Point Operations and Associativity in C, C++ and Java

CC++Java 8Programming

In C, C++, and java, we do some mathematical operations with floating point numbers. Now here we will check whether the floating point numbers are following the associativity rule or not.

The answer is NO. The floating point numbers does not follow the associativity rules in some cases. Here we will see some examples.

Example Code

#include<iostream>
using namespace std;
main() {
   float x = -500000000;
   float y = 500000000;
   float z = 1;
   cout << "x + (y + z) is: " << x + (y + z) << endl;
   cout << "(x + y) + z is "<< (x + y) + z << endl;
}

Output

x + (y + z) is: 0
(x + y) + z is 1

Here, we can see the results are not same, but theoretically we can say that they will be 1 always. Now the question comes, how this is done?

In the first case x + (y + z), the (500000000 + 1) is performing. But for the floating point round off, it is converted to 500000000 again. Now by adding -500000000 with it, it becomes 0. In the second expression, the value is (-500000000 + 500000000) = 0, then add 1 so the final result is 1.

If we use the integers, then both the expression will return the same result, which is 1.

raja
Published on 28-May-2019 12:52:44
Advertisements