I want a function that returns -1 for negative numbers and +1 for positive numbers. http://en.wikipedia.org/wiki/Sign_function It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere.
Edit: Specifically, I was looking for a function working on floats.
If all you want is to test the sign, use signbit (returns true if its argument has a negative sign). Not sure why you would particularly want -1 or +1 returned; copysign is more convenient for that, but it sounds like it will return +1 for negative zero on some platforms with only partial support for negative zero, where signbit presumably would return true.
use:
for example:
Or you may want to use some elaborated code, but casting first:
inline bool sgn_long(long x) { return ((x<0)? true: false); }
No, it doesn't exist in c++, like in matlab. I use a macro in my programs for this.
Bit off-topic, but I use this:
and I found first function - the one with two arguments, to be much more useful from "standard" sgn(), because it is most often used in code like this:
vs.
there is no cast for unsigned types and no additional minus.
in fact i have this piece of code using sgn()
This function assumes:
Surprised no one has posted the branchless, type-safe C++ version yet:
Benefits:
copysign
is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellentlyCaveats:
The
< 0
part of the check triggers GCC's-Wtype-limits
warning when instantiated for an unsigned type. You can avoid this by using some overloads:(Which is a good example of the first caveat.)