Associativity in Floating-Point Arithmetic
Floating-point arithmetic is used to represent real numbers in computing. Due to internal rounding errors, the associativity of floating-point operations can be questionable.
Problem:
Consider the following code that adds three floating-point numbers and compares their sum to 1:
cout << ((0.7 + 0.2 + 0.1) == 1) << endl; //output is 0 cout << ((0.7 + 0.1 + 0.2) == 1) << endl; //output is 1
Why do these expressions produce different results?
Answer:
Floating-point addition is not guaranteed to be associative. Changing the order in which numbers are added can alter the result due to rounding errors.
According to the paper "What Every Computer Scientist Should Know about Floating Point Arithmetic," even the parentheses in an expression can impact the result. For instance, the following expressions produce different values:
(x+y)+z x+(y+z)
where x = 1e30, y = -1e30, and z = 1. The first expression evaluates to 1, while the second evaluates to 0.
The above is the detailed content of Why Does Floating-Point Addition Produce Different Results Depending on the Order of Operations?. For more information, please follow other related articles on the PHP Chinese website!