It's not possible under IEEE754, as there is no wrap-around behaviour defined for float
or double
.
Let's assume that you are defining a
to be negative if a < 0.0
is true
. That conveniently allows us to neglect NaN cases, assuming we continue to confine the analysis to IEEE754.
Under the above assumptions it's therefore not possible for the sum of two squares to be negative. Even if a
is -0.0
then a * a
must be 0.0
. Furthermore, if a
is -inf
then a * a
must be +inf
(mathematicians are comfortable with that as the square of a countable infinity is also countable). The sum of two squares will be no less than either of the two squares comprising the sum.
However, note that formally the behaviour of floating point overflow is undefined by the C++ standard. We're fortunate that IEEE754 is ubiquitous and overflow is defined. It's possible that an implementation has a floating point scheme which does implement some sort of wraparound to negative.
To be on the safe side, test
std::numeric_limits<float>::is_iec559