Does Python optimize low-power functions?

John Ladasky john_ladasky at sbcglobal.net
Fri Dec 6 19:16:19 CET 2013


The following two functions return the same result:

    x**2
    x*x

But they may be computed in different ways.  The first choice can accommodate non-integer powers and so it would logically proceed by taking a logarithm, multiplying by the power (in this case, 2), and then taking the anti-logarithm.  But for a trivial value for the power like 2, this is clearly a wasteful choice.  Just multiply x by itself, and skip the expensive log and anti-log steps.

My question is, what do Python interpreters do with power operators where the power is a small constant, like 2?  Do they know to take the shortcut?



More information about the Python-list mailing list