Odd Test

Most commanly, the modulo % operator is used to check for an even or odd number.

Now I have a question: is there any problems with an odd number using bitwise AND, since it feels a lot more natural, checking if the rightmost bit is 1 or 0 than doing a unit check against 2

And since the 32-bit conversion does not change the rightmost bit.

AND

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

and

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

give the same result.

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

Edit: This question only takes into account values ​​that are in the 64-bit precision range since only even numbers can be represented as accurate above 2 ^ 53, and therefore both operands fail ( 9007199254740993 % 2 //0)

+8
javascript modulo bitwise-and
source share
2 answers

In JavaScript, using any bitwise operator causes the number to first be truncated to a 32-bit integer. This means that it will not work for some larger values. (Well, quite a few big values ​​:-)

The % operator does not.

edit - hey, all of you, good people who supported me: keep horses :-) C5H8NNaO4 indicates that the integer truncation process should keep a low bit, which makes it intuitive if you think about just pulling the top mantissa, and even some cursory "tests" indicate that it is working fine.

Everything becomes more complicated for really large values, which, if presented in an inaccurate floating point, can be either odd or even, as the least significant numbers are missing. In other words, when a binary metric in a floating point value results in an effective value that is larger than the mantissa capacity (I think 53 bits), you need to either consider all such numbers even (because the low bits are always zero) or you have to consider the question is uncertain.

It should be clear that I am not a mathematician.

+7
source share

If your numbers will always convert nicely to a 32-bit int, then it looks like Bitwise could be faster - I assume some javascript engines can use JIT for hardware bitwise operations. I built jsperf to check it out:

http://jsperf.com/evenness

I get very variable results in Firefox 20, sometimes it crashes a little faster, sometimes many times faster.

If your numbers may or may not convert well to 32-bit ints then stick with modulo.

0
source share

All Articles