2

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

mskfisher
  • 3,291
  • 4
  • 35
  • 48
dotty
  • 40,405
  • 66
  • 150
  • 195

4 Answers4

12

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
  • 134,786
  • 31
  • 255
  • 325
  • looking at it again myself, the OPs rule is ambiguous since zero is neither +ve or -ve. – Simon Jan 06 '10 at 14:58
  • @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 Jan 06 '10 at 15:04
  • @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 Jan 06 '10 at 15:05
  • Not sure, would it pass if the values are 0 and -3, or 0 and +3? – dotty Jan 06 '10 at 15:06
  • @dotty - that's up to you to decide - is 0 to be treated as positive or negative in your scenario? – ChrisF Jan 06 '10 at 15:11
  • 1
    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 Jun 14 '10 at 15:34
8

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
  • 40,723
  • 12
  • 105
  • 192
  • +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 Jun 14 '10 at 15:58
2

Just do something like:

if float1*float2<0
    Error
Seth Moore
  • 3,575
  • 2
  • 23
  • 33
0
function isSameSign(a,b){
  var r = a*b; 
  return (r >= 0)
}
Community
  • 1
  • 1
marcgg
  • 65,020
  • 52
  • 178
  • 231