Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, can the sum of two squared float be negative?

I have a snippet of code that compute the sum of two squared floats:

float a, b, c;
// assign some random float to b and c
a = b*b+c*c;

Can a, the sum of the two squared floats, be negative?

The original snippet is inside a function, so a different way to put the question is the following:

bool fun(float b, float c)
{
   return b*b+c*c<0;
}

Is there any pair of values for b and c that gives fun(b,c)==true?

like image 351
Alessandro Jacopson Avatar asked Nov 03 '25 07:11

Alessandro Jacopson


1 Answers

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
like image 102
Bathsheba Avatar answered Nov 06 '25 04:11

Bathsheba