Is there a standard sign function (signum, sgn) in

2018-12-31 14:46发布

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.

标签: c++ c math
24条回答
旧时光的记忆
2楼-- · 2018-12-31 15:14

Faster than the above solutions, including the highest rated one:

(x < 0) ? -1 : (x > 0)
查看更多
心情的温度
3楼-- · 2018-12-31 15:16

What about:

int sgn = x/fabs(x);

it should work out pretty good.

查看更多
倾城一夜雪
4楼-- · 2018-12-31 15:17
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
float k=10;
cout<<bool signbit(k); /* bool signbit(arg) will return "0" if arg passed is + 
                         else "1" */
return 0;
}

The above code may not serve your purpose (getting 1 or -1), but it certainly makes it way more easier to make out the sign of the data type (int, float, double etc)

查看更多
高级女魔头
5楼-- · 2018-12-31 15:19

Why use ternary operators and if-else when you can simply do this

#define sgn(x) x==0 ? 0 : x/abs(x)
查看更多
低头抚发
6楼-- · 2018-12-31 15:19

Here's a branching-friendly implementation:

inline int signum(const double x) {
    if(x == 0) return 0;
    return (1 - (static_cast<int>((*reinterpret_cast<const uint64_t*>(&x)) >> 63) << 1));
}

Unless your data has zeros as half of the numbers, here the branch predictor will choose one of the branches as the most common. Both branches only involve simple operations.

Alternatively, on some compilers and CPU architectures a completely branchless version may be faster:

inline int signum(const double x) {
    return (x != 0) * 
        (1 - (static_cast<int>((*reinterpret_cast<const uint64_t*>(&x)) >> 63) << 1));
}

This works for IEEE 754 double-precision binary floating-point format: binary64 .

查看更多
唯独是你
7楼-- · 2018-12-31 15:19
double signof(double a) { return (a == 0) ? 0 : (a<0 ? -1 : 1); }
查看更多
登录 后发表回答