首页 > 解决方案 > Why compile-time floating point calculations might not have the same results as run-time calculations?

问题描述

In constexpr: Introduction, the speaker mentioned "Compile-time floating point calculations might not have the same results as runtime calculations": enter image description here

And the reason is related to "cross-compiling".

Honestly, I can't get the idea clearly. IMHO, different platforms may also have different implementation of integers.

Why does it only affect floating points? Or I miss something?

标签: c++floating-pointlanguage-lawyerconstexprfloating-accuracy

解决方案


您绝对正确,在某种程度上,在编译时计算浮点值的问题与计算整数值的问题相同。不同之处在于任务的复杂性。在具有 16 位寄存器的系统上模拟 24 位整数数学相当容易;对于认真的程序员来说,这是一个手指练习。如果您没有本机实现,则进行浮点数学运算要困难得多。不需要浮点 constexpr 的决定部分基于这种差异:要求交叉编译器在编译时为其目标平台模拟浮点数学非常昂贵。

另一个因素是浮点计算的一些细节可以在运行时设置。四舍五入是一;处理上溢和下溢是另一回事。编译器根本不可能知道浮点计算的运行时评估的完整上下文,因此无法在编译时可靠地计算结果。


推荐阅读