I have two floating point number a
and b
. I want to check if they have different signs. The easy way is to see
bool b = a * b < 0;
But the two numbers are very small and a * b might be underflow. Any other simple way to check it?
Anyone thinking it is a duplicate question please give me an answer that exactly matches the condition a * b < 0
. Note here the sign of 0 is undefined in my question.
Let the given integers be x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit as 1 if they have opposite sign. In other words, XOR of x and y will be negative number if x and y have opposite signs.
Hence, product of two integers with unlike signs is always negative.
The product of the two integers of opposite signs is equal to the additive inverse of the product of their absolute values.
One way to add integers with different signs is to ignore the sign and find the difference between the two integers. Then give the answer the sign of the bigger integer.
Another solution is:
bool c = ((0 > a) == (0 > b));
You could use std::signbit as follows:
bool c = std::signbit(a) == std::signbit(b);
LIVE DEMO
Another way is to use std::copysign as follows:
bool c = std::copysign(a,b) == a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With