C中的浮点运算是关联的吗? [英] Are floating point operations in C associative?

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

问题描述

加法在数学上保持关联属性:

Addition mathematically holds the associative property:

(a + b) + c = a + (b + c)

在一般情况下,此属性不适用于浮点数,因为它们以有限精度表示值.

In the general case, this property does not hold for floating-point numbers because they represent values in a finite precision.

在从 C 程序生成机器代码作为优化的一部分时,是否允许编译器进行上述替换?它在 C 标准中的确切位置是什么?

Is a compiler allowed to make the above substitution when generating machine code from a C program as part of an optimization? Where does it exactly say in the C standard?

推荐答案

不允许编译器执行优化",这将导致计算的值与根据抽象机器语义计算的值不同.

The compiler is not allowed to perform "optimizations", which would result in a different value computed, than the one computed according to abstract machine semantics.

5.1.2.3 程序执行

5.1.2.3 Program execution

[#1] 这个International中的语义描述标准描述了抽象机器的行为哪些优化问题无关紧要.

[#1] The semantic descriptions in this International Standard describe the behavior of an abstract machine in which issues of optimization are irrelevant.

[#3] 在抽象机中,所有表达式都被求值由语义指定.

[#3] In the abstract machine, all expressions are evaluated as specified by the semantics.

[#13] 示例 5 浮点表达式的重新排列由于精度的限制,经常受到限制以及范围.该实施不能普遍适用加法的数学关联规则或乘法,也不是分配规则,因为舍入误差,即使没有溢出和下溢.

[#13] EXAMPLE 5 Rearrangement for floating-point expressions is often restricted because of limitations in precision as well as range. The implementation cannot generally apply the mathematical associative rules for addition or multiplication, nor the distributive rule, because of roundoff error, even in the absence of overflow and underflow.

在你的例子中:

(a + b) + c

甚至没有括号:

a + b + c

我们有

   +
  / 
  +  c
 / 
 a  b

并且编译器需要生成代码,就像 ab 相加,结果与 c 相加一样.

and the compiler is required to generate code as if a is summed with b and the result is summed with c.

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

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