signbit question
Dlang User
dlang.user at gmx.com
Thu Mar 15 18:34:01 UTC 2018
On 3/15/2018 12:39 PM, Miguel L wrote:
> On Thursday, 15 March 2018 at 17:31:38 UTC, rumbu wrote:
>> On Thursday, 15 March 2018 at 17:18:08 UTC, Miguel L wrote:
>>> On Thursday, 15 March 2018 at 16:31:56 UTC, Stefan Koch wrote:
>>>> On Thursday, 15 March 2018 at 15:28:16 UTC, Miguel L wrote:
>>>>> [...]
>>>>
>>>> integers don't have a sign-bit.
>>>> since they are not necessarily singed.
>>>> However if an integer is signed and using 1-complement
>>>> you can either do sign = var < 0 or
>>>> sign = (var & (1 << (sizeof(var)*8 - 1));
>>>> though I cannot tell which one is faster you have to experiment.
>>>
>>> Thanks. Just one more question:
>>>
>>> Is this code correct? I don't care about +0 or -0 as the calculations
>>> on f guarantee it cannot be 0 at all.
>>>
>>> int a;
>>> float f;
>>> ....
>>> if((a<0)==signbit(f)) {....}
>>> else {...}
>>
>> If you are comparing with an integer, please avoid signbit. It will
>> return 1 also for -0.0, -inf and -nan.
>>
>> Don't bother also with signbit for integer types. The compiler usually
>> outsmarts the programmer in finding the best way to compare an integer
>> with 0.
>>
>> You can simply write:
>>
>> if (a < 0 && f < 0) {...}
>>
>> This will cover the [-inf..0) but not the NaN case. You can test it in
>> a separate branch
>>
>> if (isNaN(f)) {...}
>
> There are various in my code there are more than two variables, and i'd
> like to check when their signs differ.I am trying to avoid this, maybe
> there is no point in it:
>
> if(!((a>=0 && f>=0) || (a<0 && f<0))){
> //signs are different
> ....
> }
>
> Thanks, anyway
You could simplify that to this:
if ((a < 0) != (f < 0))
{
}
Or if you have more than two variables you could do something like this:
bool AllSameSign(double[] args ...)
{
//Only need to check if there are more than one of them
if (args.length > 1)
{
//Compare arg[0] to all the other args.
for (int i = 1; i < args.length; i++)
{
if ((args[0] < 0) != (args[i] < 0))
{
return false;
}
}
}
return true;
}
Which you could call like this, with as many variables as you like:
AllSameSign(a,f);
More information about the Digitalmars-d-learn
mailing list