The behaviour of floating point division by zero

后端 未结 7 1729
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 02:39

Consider

#include 
int main()
{
    double a = 1.0 / 0;
    double b = -1.0 / 0;
    double c = 0.0 / 0;
    std::cout << a << b          


        
7条回答
  •  抹茶落季
    2020-12-03 03:00

    Quoting cppreference:

    If the second operand is zero, the behavior is undefined, except that if floating-point division is taking place and the type supports IEEE floating-point arithmetic (see std::numeric_limits::is_iec559), then:

    • if one operand is NaN, the result is NaN

    • dividing a non-zero number by ±0.0 gives the correctly-signed infinity and FE_DIVBYZERO is raised

    • dividing 0.0 by 0.0 gives NaN and FE_INVALID is raised

    We are talking about floating-point division here, so it is actually implementation-defined whether double division by zero is undefined.

    If std::numeric_limits::is_iec559 is true, and it is "usually true", then the behaviour is well-defined and produces the expected results.

    A pretty safe bet would be to plop down a:

    static_assert(std::numeric_limits::is_iec559, "Please use IEEE754, you weirdo");
    

    ... near your code.

提交回复
热议问题