views:

203

answers:

5

Hay guys, i have 2 floats, which both comes from input boxes.

I need to compare these 2 floats, if one is negative and one is positive thrown an error. If they're both positive, or both negative, thats fine.

Any ideas?

Thanks

+9  A: 

Multiply them together.

If the answer is positive then they are both the same sign.

If the answer is negative then they are of opposite sign.

If the answer is zero (within some value to take care of rounding error) then one or both are zero and you'll have to check them individually. You'll then have to decide whether 0 to be treated as positive or negative in your scenario.

ChrisF
what about zero?
Simon
ChrisF
looking at it again myself, the OPs rule is ambiguous since zero is neither +ve or -ve.
Simon
if they're both zero, thats fine. Would this solution work?
dotty
@dotty yes, it would work, and it is a neat solution except when one or other value is zero. What does your rule say when only one value is zero?
Simon
@dotty - if they are both zero then the answer will be zero (actually within rounding error of zero, but that's another matter). In any case a zero result will mean you have to check each input individually to see if it's positive or negative.
ChrisF
Not sure, would it pass if the values are 0 and -3, or 0 and +3?
dotty
@dotty - that's up to you to decide - is 0 to be treated as positive or negative in your scenario?
ChrisF
Well since we're talking about IEEE standard floating point we have +0 and -0 as two separate numbers... although I'm not sure how you'd detect them without doing type puning and comparing them as int's (this has a potential issue in that there are insane platforms that use a different byte order for ints and floats...)
Spudd86
+2  A: 

Just do something like:

if float1*float2<0
    Error
smoore
A: 
function isSameSign(a,b){
  var r = a*b; 
  return (r>0 || r==0)
}
marcgg
+4  A: 

Although detection of the sign of the product can be done, it's not what you are interested in. Especially if you're going to use it on large volumes of floats (eg to detect a zero crossing in a time stream).

The simplest way is to exactly express what you ask for: is the sign of a equal to the sign of b?

function samesign( a, b ) {
  var aPositive = a >= 0;
  var bPositive = b >= 0;
  return aPositive == bPositive;
}

Or shorter:

function samesign( a, b ) { return (a>=0) == (b>=0); }
xtofl
+1 Better solution than a multiplication. As everyone notes in other answers, it is important to code clearly and without tricks. Unless you have other concers like optimization
Toad
A: 

Someone with almost the same question, but worried about +0 and -0

http://stackoverflow.com/questions/2922619/how-to-efficiently-compare-the-sign-of-two-floating-point-values-while-handling-n

Spudd86