Search code examples
pythonbitwise-operatorsbit-shiftoperator-precedenceparentheses

Python - Removing parenthesis around bit-wise shift operators giving different results during addition


I was coding for multiplication using Karatsuba Algorithm and it required some bit shifting. Keeping it short, I needed to convert this mathematical expression to programming statement:

mathematical formula for karatsuba

Without any parenthesis and confirming that addition (+) has precedence over bit-wise shift operators (<<), I wrote this statement:

product = (high_part<<m)<<m + middle_part<<m + low_part

For high_part, middle_part, low_part = 0, 0, 1, this gives product = 0. The correct answer, if you calculate, is 2.

I get different answers with different order of the variables in the statement. For example, high_part, middle_part, low_part = 0, 0, 1 and

product = middle_part<<m + low_part + (high_part<<m)<<m

gives product = 4.

Well, when I put parenthesis around the three addends, I get the correct answer (product = 2):

product = ((high_part<<m)<<m) + (middle_part<<m) + (low_part)

Is this a precedence issue or am I missing something weird here?


Solution

  • If you look carefully at the Python documentation on operator precedence, you will see that + apply before << (the same way * apply before +).