user1899020
user1899020

Reputation: 13575

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

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.

Upvotes: 14

Views: 4531

Answers (2)

Stamen Rakov
Stamen Rakov

Reputation: 476

Another solution is:

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

Upvotes: 3

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

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;

Upvotes: 10

Related Questions