Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why is INFINITY - INFINITY calculated to -NAN?

+2 votes
asked Mar 1, 2018 by MatsOla Karlsson

I have a C-function which tests that an x - x expression, where x is a double, is not reduced to 0.

Why, when x is INFINITY, does x - x give the wrong result -NAN (negative) instead of NAN (positive)?

* Test that the compiler does not optimise x-x to zero. Also test that INF-INF is correctly calculated.
* The calculation expression is regarded highly prone to be reduced to zero by a sloppy compiler.
* Returns 0x1 if successful. Otherwise an even value less than 0xf is returned.
static unsigned int
    unsigned int res = 0x0u;
    const unsigned long long pattInf  = 0x7ff0000000000000uLL;
    const unsigned long long pattNan  = 0x7ff8000000000000uLL;
    const unsigned long long pattZero = 0x0000000000000000uLL;
    const double x = *(double*)&pattInf;

    const double XsubX = x - x;

    if (*(unsigned long long*)&XsubX == pattNan)
        res = 0x1u;   // Correct subtraction INFINITY - INFINITY = NAN
    else if (*(unsigned long long*)&XsubX == pattZero)
        res = 0x2u;   // Incorrect subtraction INFINITY - INFINITY = 0
        res = 0xeu;

    return res;
}   // infInfSubtraction()

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.