Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any simple way to check if two numbers have different signs?

Tags:

c++

math

sign

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.

like image 556
user1899020 Avatar asked Dec 01 '15 21:12

user1899020


People also ask

How do you know if two numbers are different signs?

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.

What is the product of two numbers having different signs?

Hence, product of two integers with unlike signs is always negative.

What is the product of 2 numbers of opposite signs?

The product of the two integers of opposite signs is equal to the additive inverse of the product of their absolute values.

How do you find the sum of two integers with different signs?

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.


2 Answers

Another solution is:

bool c = ((0 > a) == (0 > b));

like image 162
Stamen Rakov Avatar answered Nov 14 '22 06:11

Stamen Rakov


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;
like image 24
101010 Avatar answered Nov 14 '22 05:11

101010