I want to write an IEEE-754 compliant division in C++, especially with regard to division by zero handling: positive/0->Inf
, negative/0->-Inf
, everything else/0->NaN
.
While a simple C++ division on my machine results in this very behavior, the C++ standard does not mandate this semantics. It is instead undefined, so I cannot rely on it.
So what is the fastest way to implement this in C++? Of course I can do an explicit test like this:
double fdiv64(double numerator, double denominator)
{
using limits=std::numeric_limits<double>;
if (denominator==0.0) {
if (numerator>0.0) {
return limits::infinity();
} else if (numerator<0.0) {
return -limits::infinity();
} else {
return limits::quiet_NaN();
}
} else {
return numerator/denominator;
}
}
But this introduces extra branches and is totally superfluous on my machine, as I get the right behavior on it anyway. There does not seem to be a compiler intrinsic that does IEEE-754 compliant division. I could use inline assembly but this is quite unportable, too.
So what is the fastest way to do this division?