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.
Faster than the above solutions, including the highest rated one:
What about:
it should work out pretty good.
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)
Why use ternary operators and if-else when you can simply do this
Here's a branching-friendly implementation:
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:
This works for IEEE 754 double-precision binary floating-point format: binary64 .