Unfortunately floating point math is not exact. Therefore, it's possible that "sum" could be ever so slightly greater than 1, and therefore you would be trying to take the square root of an actual negative (not just -0).
One solution in this case would be to use fabs(1 - sum). Assuming that sum is never much more than 1, which it shouldn't be, this wouldn't change your answer too much but would ensure you never put a negative into the sqrt().
Bookmarks