当 x = 10³⁰,y = -10³⁰ 和 z = 1 时,为什么 (x+y)+z 和 x+(y+z) 不同?

When x = 10³⁰, y = -10³⁰ and z = 1, why do (x+y)+z and x+(y+z) differ?

What Every Computer Scientist Should Know About Floating-Point Arithmetic 提出以下声明:

Due to roundoff errors, the associative laws of algebra do not necessarily hold for floating-point numbers. For example, the expression (x+y)+z has a totally different answer than x+(y+z) when x = 1030, y = -1030 and z = 1 (it is 1 in the former case, 0 in the latter).

他们的例子是如何得出结论的?也就是说,(x+y)+z=1 和 x+(y+z)=0?

我知道代数的结合律,但在这种情况下我看不到问题。在我看来,x 和 y 都会溢出,因此它们都有一个不正确但仍在范围内的整数值。由于 x 和 y 将是整数,因此它们应该相加,就像应用关联性一样。

舍入误差和浮点运算的其他方面,适用于整个浮点运算。虽然浮点变量可以存储的某些值是整数(在它们是整数的意义上),但它们不是整数类型的。浮点变量不能存储任意大的整数,就像整数变量一样。虽然环绕整数运算将使任何无符号整数类型的 a 和 b 为 (a+b)-a=b,但浮点运算并非如此。溢出规则不同

When x = 10^(30), y = -10^(30) and z = 1, why do (x+y)+z and x+(y+z) differ?

除了 答案,请注意结果 不同。

即使操作数的浮点类型没有足够的进动来准确编码和 1 + 1030,如 binary64, some languages, like C, allow intermediate calculations to compute using higher precision (like maybe long double as binary128) 导致共同的总和-1.