浮点加法和乘法是结合的吗? [英] Is floating-point addition and multiplication associative?

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

问题描述

在添加三个浮点值并将它们与 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 时,表达式 (x+y)+z 与 x+(y+z) 的答案完全不同(前者为 1,后者为 0).

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天全站免登陆