c - C中的浮点运算是关联的吗?

标签 c math floating-point compiler-optimization

加法在数学上具有结合性质:

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

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

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

最佳答案

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

5.1.2.3 Program execution

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

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

[#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 相加。

关于c - C中的浮点运算是关联的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13913017/

相关文章:

c++ - 我是否正确实现了这一点?

c - 如何在 C 中可移植地打印 int64_t 类型

php - 在 MongoDB 中求和 "column"

compiler-errors - to_float()和除法错误

java - 比较数学表达式

c++ - vsnprintf 返回超过给定缓冲区大小的大小

c - 在输出文件中显示客户端的IP地址?

java - 从频率数组中获取中值?

c# - 在代码隐藏中将表达式从文本框转换为数学表达式

c - 预除分母时数值不稳定的风险是什么?