 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Floating Point Operations and Associativity in C, C++ and Java
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.
