Question

Most commanly the modulo operator % is used to test against an even or odd Number.

Now my question is, is there any Problem testing against an odd number using a bitwise AND, as it feels much more natural testing whether the rightmost bit is 1 or 0 than doing a modulo check against 2

And as the 32 bit conversion does not change the rightmost bit.

Both

(1 + Math.pow(2,52)) & 1 //1

and

(1 + Math.pow(2,52)) % 2 //1

yield the same result.

Is there a reason to prefer the modulo operator over the bitwise?

Edit: This question only accounts for values that fall in the range of 64bit precision as only even numbers can be represented precise above 2^53 and therefore both operands fail (9007199254740993 % 2 //0)

Was it helpful?

Solution

In JavaScript, using any bitwise operator causes the number to be first truncated to a 32-bit integer. That means it won't work for some larger values. (Well, quite a few larger values :-)

The % operator doesn't do that.

edit — hey all you nice people who've upvoted me: hold your horses :-) C5H8NNaO4 points out that the integer truncation process should preserve the low bit, which makes intuitive sense if you think about just lopping off the top part of the mantissa, and indeed some cursory "tests" indicate that it seems to work fine.

Things get more complicated of course for really large values, which when represented in imprecise floating point may be either odd or even, since the least-significant digits are missing. In other words, when the binary exponent in a floating point value results in an effective value that's larger than the mantissa capacity (53 bits I think), then you either have to consider all such numbers even (because the low bits are always zero) or else you have to consider the question indeterminate.

It should be clear that I'm not a mathematician.

OTHER TIPS

If your numbers will always convert nicely to a 32 bit int, then it looks like Bitwise can be faster -- I'm guessing some javascript engines can JIT it to hardware bitwise operations. I've constructed a jsperf to test it:

http://jsperf.com/evenness

I get very variable results on Firefox 20, sometimes the Bitwise is slightly faster, sometimes many times faster.

If your numbers may or may not convert nicely to 32 bit ints, then stick to modulo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top