含Infinity与NaN的浮点运算结果:遵循IEEE 754还是编译器依赖?
1. Are Infinity and NaN floating-point operations explicitly defined in IEEE 754?
Absolutely—IEEE 754 (the global standard for floating-point arithmetic) strictly defines the behavior of all operations involving inf (infinity) and NaN (Not a Number). This consistency is a core design goal of the standard, ensuring predictable results across different hardware, compilers, and programming environments. Some key defined behaviors include:
inf + inf=inf(adding two positive infinities retains positive infinity)inf + (-inf)=NaN(combining positive and negative infinity is an indeterminate operation with no valid numerical result)0 * inf=NaN- Any operation involving
NaN(e.g.,NaN + 5,inf * NaN) returnsNaN
These rules aren’t optional—any implementation claiming IEEE 754 compliance must adhere to them.
2. In Visual Studio 2017, results like inf + inf = inf and inf + (-inf) = -nan(ind): do they follow IEEE 754 or depend on the compiler?
These results are strictly following the IEEE 754 standard—Visual Studio 2017 (and nearly all modern compilers) implements IEEE 754 correctly by default. Let’s break down your examples:
inf + inf = inf: This is directly specified in the standard; adding two positive infinities logically remains positive infinity.inf + (-inf) = -nan(ind): The standard mandates this operation returns aNaN(since it’s mathematically undefined). The-nan(ind)notation (where "ind" stands for "indeterminate") is just Visual Studio’s way of displaying this specific type of NaN—other compilers might shownanornan(ind)without the negative sign, but the underlying value is still a valid IEEE 754 NaN.
While some compilers offer options to disable strict IEEE 754 compliance (for niche performance optimizations), Visual Studio 2017 uses compliant behavior by default for these floating-point operations. What you’re seeing is exactly what the standard prescribes.
内容的提问来源于stack exchange,提问作者Nowibananatzki

