Search code examples
pythonpow

working of exponential operator ** in Python


I am running a python script where I am computing following:

t - 2 ** (j - 1) * l

Where t = 302536, j = 6, l = 0.

This returns me 302536 (t), I am not able to understand how. As per me the result should have been 302535 (t - 1).

2 ** (j - 1) * l results in 0 which according to me should have resulted in 1 as (j - 1) * l results in 0.

How is this being computed?


Solution

  • The only thing that binds tighter than power is parentheses. Python (and every other language that natively supports a power operator that I've seen) follows arithmetic convention on this one, so you don't need to memorize different sets of conflicting rules. You operation can be explicitly rewritten as follows:

    t - ((2 ** (j - 1)) * l)
    

    As you pointed out, setting l = 0 discards much of the computation. It's just that it discards everything but t itself.

    You could make such things explicit by using the function form of the power operator. Any of the following imports would work for the example below:

    from math import pow
    from operator import pow
    from operator import __pow__ as pow
    from numpy import pow
    

    It seems like you wanted/expected

    t - pow(2, (j - 1) * l)
    

    But instead got

    t - pow(2, j - 1) * l