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)
If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd.
Odd numbers stick in our brain more, are harder to digest -- and as a result gain extra meanings. In western culture the numbers that attract the most superstition, three, seven and 13, are all odd. Room 101 is a much scarier place than Room 100 because 101 is arithmetically more challenging than 100.
Imparnumerophobia (from Latin impar, "odd", and numerus, "number") is the fear of odd numbers.
Chefs often acknowledge the importance of presenting odd numbers of elements on the plate, as recommended in chefs' guides on the art of plating (e.g., Styler & Lazarus, 2006), in an attempt to enhance the visual appeal of a meal.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With