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.
CodePudding user response:
Restricting this answer to IEEE754, using /-Inf as some sort of starting value brings a fair bit of trouble.
Under IEEE754,
- Inf * 0.0 = NaN
- -Inf * 0.0 = Inf * -0.0 = -NaN
- Inf * Inf = -Inf * -Inf = Inf
- -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.