Home  >  Article  >  Backend Development  >  Floating-point arithmetic and associativity in C, C++, and Java

Floating-point arithmetic and associativity in C, C++, and Java

王林
王林forward
2023-08-28 09:09:111223browse

Floating-point arithmetic and associativity in C, C++, and Java

In C, C and Java, we use floating point numbers to perform some mathematical operations. Now we will check whether floating point numbers follow the associativity rules.

the answer is negative. In some cases, floating point numbers do not follow the associativity rules. Here we'll 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 that the results are not the same, but in theory we can say that they are always 1. Now the question arises, how is this done?

In the first case x (y z), (500000000 1) is executing. But for floating point numbers After rounding, it is converted again to 500000000. Now add -500000000 and it becomes 0. In the second expression, the value is (-500000000 500000000) = 0, then 1 is added, so the final result The result is 1.

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

The above is the detailed content of Floating-point arithmetic and associativity in C, C++, and Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete