Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two floats to see if they're both negative, or both positive

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

like image 661
dotty Avatar asked Dec 30 '25 07:12

dotty


2 Answers

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.

like image 150
ChrisF Avatar answered Jan 01 '26 21:01

ChrisF


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); }
like image 43
xtofl Avatar answered Jan 01 '26 22:01

xtofl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!