Sign safer on this way ?

Started by
9 comments, last by alvaro 8 years, 5 months ago

I'll remeber to call my function sign_bit if I ever write that "optimized" version

http://en.cppreference.com/w/cpp/numeric/math/signbit
That one can return positive or negative for zero... Which some algorithms probably need, but again isn't optimal or desirable for other cases.
Guess I'm down to sign_dichotomy :lol:

I agree that the sign of a floating point number is a binary result; either a positive sign or a negative sign, so boolean is a better return type... or an enum with two choices if you prefer. If you have it, use std::signbit() to do it.

Unless your platform doesn't like mixing register types - after working with PowerPC, I'm wary, as code like that would stall the CPU :o
A lot of algorithms will also probably assume or rely on zero having a single defined result, instead of the result changing depending on how you computed that zero.
Advertisement

It seems some people may have forgotten -- or perhaps never knew -- that in floating point math zero has a sign.


Oh, I know. And it's soooo annoying. smile.png

You can have both +0.0 and -0.0, and it does make a difference in certain floating point operations. It can trigger the difference between positive or negative infinity, which is about as dramatic a difference as floating point can get.


Not really. If you are doing something like 1.0 / 0.0, you are probably computing something like a slope (a point in the projective line, if you like that kind of language), and in that case +infinity and -infinity are similar as -0.0 and +0.0.

I agree that the sign of a floating point number is a binary result; either a positive sign or a negative sign, so boolean is a better return type... or an enum with two choices if you prefer.


Except you are almost always going to be computing the sign of a difference, and you won't be seeing a whole lot of -0.0, so 0 will look positive to you. This has unfortunate consequences, like sign(a-b) == -sign(b-a) not holding. The sign of both -0.0 and +0.0 should be 0, following the definition of the sign function.

This topic is closed to new replies.

Advertisement