For floating point values, is it guaranteed that a + b
is the same as1 b + a
?
I believe this is guaranteed in IEEE754, however the C++ standard does not specify that IEEE754 must be used. The only relevant text seems to be from [expr.add]#3:
The result of the binary + operator is the sum of the operands.
The mathematical operation "sum" is commutative. However, the mathematical operation "sum" is also associative, whereas floating point addition is definitely not associative. So, it seems to me that we cannot conclude that the commutativity of "sum" in mathematics means that this quote specifies commutativity in C++.
Footnote 1:
"Same" as in bitwise identical, like memcmp
rather than ==
, to distinguish +0 from -0. IEEE754 treats +0.0 == -0.0
as true, but also has specific rules for signed zero. +0 + -0
and -0 + +0
both produce +0
in IEEE754, same for addition of opposite-sign values with equal magnitude. An ==
that followed IEEE semantics would hide non-commutativity of signed-zero if that was the criterion.
Also, a+b == b+a
is false with IEEE754 math if either input is NaN.
memcmp
will say whether two NaNs have the same bit-pattern (including payload), although we can consider NaN propagation rules separately from commutativity of valid math operations.
std::strtod("nan")+0.0 == 0.0+std::strtod("nan")
is false. But I doubt that's what you mean. – Hilaryhilberta+b == b+a
is not the same as asking if it's commutative, because==
is different from memcmp. The most likely non-commutativity in a system similar to IEEE754, like some software-FP emulation, would probably be with signed-zero or different NaN payloads. (e.g.0 + -0
might always take the sign of the left-hand operand, vs in IEEE754 always being+0
.) But it might well still implement-0 == +0
IEEE semantics. (Also,a+b == b+a
is false for IEEE754 if either a or b is NaN. Again, memcmp would actually check commutativity). – Claiborne--fast-math
or-Ofast
, in which anything can happen. – Richter