C 中的浮点运算是否具有关联性?

编程入门 行业动态 更新时间:2024-10-24 22:19:24
本文介绍了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] 本国际中的语义描述标准描述了一个抽象机器的行为哪些优化问题无关紧要.

[#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

并且编译器需要生成代码,就好像a与b相加,结果与c相加.

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

更多推荐

C 中的浮点运算是否具有关联性?

本文发布于:2023-10-28 08:34:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关联性   浮点

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!