是浮点加法还是乘法关联? [英] Is Floating point addition and multiplication associative?

查看:137
本文介绍了是浮点加法还是乘法关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在添加三个浮点值并将其与1比较时遇到了问题。

I had a problem when I was adding three floating point values and comparing them 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

为什么这些值会不同?

推荐答案

浮点加法不一定是关联的。

Floating point addition is not necessarily associative. If you change the order in which you add things up, this can change the result.

主题的标准文件是每个计算机科学家应该知道的浮点算术。它给出了以下示例:

The standard paper on the subject is What Every Computer Scientist Should Know about Floating Point Arithmetic. It gives the following example:


另一个灰色区域涉及括号的解释。由于四舍五入误差,代数的关联定律不一定适用于浮点数。例如,当x = 1e30,y = -1e30和z = 1时(在前一种情况下为1,在后一种情况下为0),表达式(x + y)+ z具有完全不同于x +(y + z) )。

Another grey area concerns the interpretation of parentheses. 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 = 1e30, y = -1e30 and z = 1 (it is 1 in the former case, 0 in the latter).

这篇关于是浮点加法还是乘法关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆