C++ 标准是否对浮点数的表示有任何规定?

Does the C++ standard specify anything on the representation of floating point numbers?

对于 std::is_floating_point<T>::valuetrue 的类型 T,C++ 标准是否指定了 T 应该实现的方式?

例如,T是否必须遵循sign/mantissa/exponent表示?还是可以完全随意?

来自 N3337:

[basic.fundamental/8]: There are three floating point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The value representation of floating-point types is implementation-defined. Integral and floating types are collectively called arithmetic types. Specializations of the standard template std::numeric_limits (18.3) shall specify the maximum and minimum values of each arithmetic type for an implementation.

如果您想检查您的实现是否使用 IEEE-754,您可以使用 std::numeric_limits::is_iec559:

static_assert(std::numeric_limits<double>::is_iec559,
              "This code requires IEEE-754 doubles");

该区域还有许多其他辅助特征,例如 has_infinity, quiet_NaN and more

std::is_floating_point的想法是让不同来源的用户代码更好地协同工作。从技术上讲,您可以将 int 指定为 std::is_floating_point 而不会导致未定义的行为。但是假设你有一些模板库必须重复除以 T n。为了加快处理速度,库创建了一个 T ni = 1 / n 并用 ni 乘法代替了 n 的除法。这适用于浮点数,但不适用于整数。因此,库仅在 std::is_floating_point<T>::value == true 时才正确地进行优化。如果你撒谎,代码从标准的角度来看可能仍然有效,但从逻辑的角度来看是不正确的。因此,如果您编写的 class 的行为类似于更大的 float,则将其标记为 std::is_floating_point,否则不要这样做。这应该让您获得最佳和正确的代码。

不需要特定的实现。 C++ 标准根本没有谈论它。 C 标准对浮点数假定的概念模型进行了相当多的详细说明,其中包含符号、指数、某些基数 b 中的尾数等等。然而,它明确指出这纯粹是描述性的,而不是对实现的要求(C11,脚注 21):

The floating-point model is intended to clarify the description of each floating-point characteristic and does not require the floating-point arithmetic of the implementation to be identical.

就是说,尽管细节可能有所不同,但至少在我看来,生成(例如)不符合 公平 [=22] 的 double 的一致实现=] 与通常的模型(即有效数和指数)密切相关是很困难的(或者至少很难与竞争性能相关)。不过,让它以其他方式变化并不是特别困难,例如重新排列顺序或使用不同的基数。

std::numeric_limits<T>::digits(和 std::numeric_limits<T>::digits10)的定义相当直接地暗示,列为浮点类型的内容必须在相当宽的范围内对所有数字保持(至少近似)相同的精度数量级。到目前为止,实现这一点的最明显的方法是将一些 bits/digits 专用于有效数字,以及一些其他(单独的)位集专用于指数。

C 标准有一个 "annex"(在 C11 中是附件 F),它阐明了 C 的实现符合 IEC 60559(IEEE 754 的后续标准)的含义。一个实现符合附件 F 必须具有 IEEE 表示浮点数。但是,实施本附件是可选的;核心标准特别避免提及浮点数的表示形式。

我不知道是否有 C++ 的等效附件。它没有出现在 N3337 中,但这可能只是意味着它是单独分发的。 std::numeric_limits<floating-type>::is_iec559 的存在表明 C++ 委员会至少 考虑过 ,但可能没有 C 委员会考虑得那么详细。 (C++ 标准没有表示为对 C 标准的一组编辑,这一直是一个该死的耻辱。)