Be a Supporter!

C++ Comparing signs of two numbers

  • 317 Views
  • 1 Reply
New Topic Respond to this Topic
Wolftacular
Wolftacular
  • Member since: Jul. 6, 2007
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
C++ Comparing signs of two numbers Feb. 6th, 2013 @ 11:31 PM Reply

So I was writing up a little program to do matrices for me and while writing my program I was faced with a situation:

I had to compare the signs of two numbers x and y and determine if they had different signs or not.

So, of course, first thing that came to my mind was to multiply x*y

if ( x*y > 0 ){
//numbers have same sign
} else {
//numbers have different signs
}

Perfect! Until I plugged in big numbers and I got overflows. So for the sake of my program's integrity and my learning (since I wasn't planning on using big numbers), I ran a quick search on a good way of accomplishing such a task, and ran into a bunch of solutions, most of which I honestly didn't understand (I'm still a beginner), until it occurred to me...

If the problem is that the product of the two numbers is too big, what if I divided each number by itself? Well, no, because then my numbers would both become positive 1s, regardless of what their original signs were. But what about dividing each number by its own absolute value??

//abs() returns the absolute value of a number
if( ( (x/abs(x)) * (y/abs(y)) ) > 0){
//numbers have same sign
} else {
//numbers have different signs
}

Surely someone had thought of this before. So I just wanted to ask why this would be a bad solution, or rather, why this isn't the best solution?

Thank you all for your time!

Diki
Diki
  • Member since: Jan. 31, 2004
  • Offline.
Forum Stats
Moderator
Level 13
Programmer
Response to C++ Comparing signs of two numbers Feb. 7th, 2013 @ 12:16 AM Reply

You could just write a simple function to do it.
No need for multiplication or division.

template <class NumTy>
bool matchingSigns(NumTy a, NumTy b) {
    return a < (NumTy)0 == b < (NumTy)0;
}

Since it's a template it will work for any given number type, be it a signed or unsigned char/short/int, or a float/double.
The casting to NumTy is just there to prevent potential compiler warnings.

The logic is pretty straightforward. Check if both numbers are less than zero, which will result in two bool results. Two positives will yield two false values, and two negatives will yield two true values. True equals true , and false equals false, so either of those cases will cause the function to return true, otherwise the signs don't match and you'll get a false return value.
Hopefully that wasn't too confusing of an explanation.

The function will also most likely be inlined automatically by the compiler, so it will be as if the function was never there.