Is there a standard sign function (signum, sgn) in C/C++?
Yes, depending on definition.
C99 and later has the signbit()
macro in <math.h>
int signbit
(real-floating x
);
The signbit
macro returns a nonzero value if and only if the sign of its argument value is negative. C11 §7.12.3.6
Yet OP wants something a little different.
I want a function that returns -1 for negative numbers and +1 for positive numbers. ... a function working on floats.
#define signbit_p1_or_n1(x) ((signbit(x) ? -1 : 1)
Deeper:
OP's question is not specific in the following x
cases: 0.0, -0.0, +NaN, -NaN
.
A classic signum()
returns +1
on x>0
, -1
on x<0
and 0
on x==0
.
Many answers have already covered that, but do not address x
as -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 return 0.0, 0.0, 0.0
.
int signnum_typical(double x) {
if (x > 0.0) return 1;
if (x < 0.0) return -1;
return 0;
}
Instead, I propose this functionality: On -0.0, +NaN, -NaN
, it returns -0.0, +NaN, -NaN
.
double signnum_c(double x) {
if (x > 0.0) return 1.0;
if (x < 0.0) return -1.0;
return x;
}
x==0
. According to IEEE 754, negative zero and positive zero should compare as equal. – Barbellatesgn()
of your comment is a reasonable view of how to handle zeros. OP only indirectly specified sign of zero with a link. Another reasonable view of the "sign" is to return 1,-1 on +zero,-zero. Sometimes the sign of zero makes a difference. It depends on user's need. Also NaN is a consideration as OP specifiedfloat
. – Rathbun