signbit question

Seb seb at wilzba.ch
Thu Mar 15 16:18:56 UTC 2018


On Thursday, 15 March 2018 at 15:28:16 UTC, Miguel L wrote:
> Why does std.math.signbit only work for floating point types?
> Is there an analogue function for integer types?

I guess because for integers you don't need to distinguish 
between +0.0 and -0.0, so no one bother until now to add it to 
std.math.

That being said there are a few options for integer types:

---
import std.math, std.stdio;

void main()
{
     foreach (a; -1 .. 2)
     {
         "a:".writeln(a);
         signbit(cast(double) a).writefln!"signbit:  %2d";
     	(cast(uint) a >> a.sizeof * 8 - 1).writefln!"bitshift: %2d";
     	(a < 0).writefln!"< 0:\t  %2d";
         writeln;
     }
}
---

https://run.dlang.io/is/pts6dj

The first option is a bit slower for integers and the second and 
third option generate equivalent assembly [1], so I would 
recommend `a < 0` for integer types.

[1] https://godbolt.org/g/4ohTJx

> what is the best way to compare the sign of a float with the 
> sign of an integer?

Ideas:

1) Make a PR to signbit to add integer support
2) Create your own signsbit a la:

---
auto signbit(A)(A a)
{
     static import std.math;
     import std.traits : isIntegral;
     static if (isIntegral!A)
         return a < 0;
     else
         return std.math.signbit(a);
}
---


More information about the Digitalmars-d-learn mailing list