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.
I ran into this just today. So fine, there's no standard way but...
Since the OP just needed to magnify the output range and re-centre it on 0, (-1 to 1 not 0 to 1) why not just double it and subtract 1?
I used this:
(x<0)*2-1
Or, forcing a bit shift:
(x<0)<<1-1
But the compiler will likely optimize that anyway.
While the integer solution in the accepted answer is quite elegant it bothered me that it wouldn't be able to return NAN for double types, so I modified it slightly.
Note that returning a floating point NAN as opposed to a hard coded
NAN
causes the sign bit to be set in some implementations, so the output forval = -NAN
andval = NAN
are going to be identical no matter what (if you prefer a "nan
" output over a-nan
you can put anabs(val)
before the return...)Yes, depending on definition.
C99 and later has the
signbit()
macro in<math.h>
Yet OP wants something a little different.
Deeper:
The post is not specific in the following cases,
x = 0.0, -0.0, +NaN, -NaN
.A classic
signum()
returns+1
onx>0
,-1
onx>0
and0
onx==0
.Many answers have already covered that, but do not address
x = -0.0, +NaN, -NaN
. Many are geared for an integer point-of-view that usually lacks Not-a-Numbers (NaN) and -0.0.Typical answers function like
signnum_typical()
On-0.0, +NaN, -NaN
, they return0.0, 0.0, 0.0
.Instead, propose this functionality: On
-0.0, +NaN, -NaN
, it returns-0.0, +NaN, -NaN
.I don't know of a standard function for it. Here's an interesting way to write it though:
Here's a more readable way to do it:
If you like the ternary operator you can do this:
Apparently, the answer to the original poster's question is no. There is no standard C++
sgn
function.It seems that most of the answers missed the original question.
Not in the standard library, but there is in
boost
, which might as well be part of the standard.http://www.boost.org/doc/libs/1_47_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/sign_functions.html