Search code examples
c++stlstdmultiplicationinfinity

Regarding arithemetic operations with std::numeric_limits<T>::infinity()


I have a peculiar usecase where I have some edges w/ double weights set initially to std::numeric_limits<double>::infinity(). These weights will be set to something else later on in program execution.

Now that we have the context, here is the main issue. I need to compare these edge weights to the square of some weight that I compute, and to account for the squaring of my computed weight, I will also have to square the edge weights. Of course, this will result in an initial multiplying of infinity by infinity. I am wondering if multiplying a double set to std::numeric_limits<double>::infinity() by itself is defined behavior. Can I expect it to remain unchanged?

I could not find any documentation even on cppreference.


Solution

  • Restricting this answer to IEEE754, using +/-Inf as some sort of starting value brings a fair bit of trouble.

    Under IEEE754,

    1. Inf * 0.0 = NaN
    2. -Inf * 0.0 = Inf * -0.0 = -NaN
    3. Inf * Inf = -Inf * -Inf = Inf
    4. -Inf * Inf = -Inf

    Inf multiplied by any positive floating point value (including a subnormal value) is Inf, and similarly for -Inf.

    In other words, you need to treat +0.0 and -0.0 as special cases when multiplying, and is one of those rare cases where a signed negative zero produces a different result. Use std::isnan to test, if you cannot adopt some other scheme.