7

I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand

In [1]: 2**2
Out[1]: 4

In [2]: 2**2**2
Out[2]: 16

In [3]: 2**2**2**2
Out[3]: 65536

In [4]: 2**2**2**2**2 

The answer to [4] is not 4294967296L, it's a very long number, but I can't really figure out why.

The number can be found here: http://pastie.org/475714

(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)
(Mac OS X 10.5.6, Python 2.5.1)

2
  • And what is that number that is not 4294967296L?
    – joce
    Commented May 12, 2009 at 15:39
  • provided link for number
    – fforw
    Commented May 12, 2009 at 15:44

5 Answers 5

16

Python is going right to left on the mathematical power operation. For example, IN[2] is doing:

2**(4) = 16

IN[3] = 2222 = 22**(4) = 2**16 = 65536

You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out.

2^65536 = extremely huge

7

The precedence of the ** operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:

2**2**2**2 == (2**(2**(2**2)))
4

This is because the order of precedence in Python causes this equation to be evaluated from right-to-left.

>>> 2**2
4
>>> 2**2**2
16
>>> 2**(2**2)
16
>>> 2**2**2**2
65536
>>> 2**2**(2**2)
65536
>>> 2**(2**(2**2))
65536
>>> 2**2**2**2**2
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**2**2**(2**2)
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**2**(2**(2**2))
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**(2**(2**(2**2)))
57896044618658097711785492504343953926634992332820282019728792003956564819968L
>>> 2**255
57896044618658097711785492504343953926634992332820282019728792003956564819968L
4

As the other answers already said, it's because ** is evaluated from right to left. Here is the documentation link, where all the precedences are described.

2
  • Imagine for a moment if it was evaluated in the other direction - surely we'd expect the exact same answer since the original statement is symmetrical. Commented May 13, 2009 at 23:44
  • 1
    I am not sure I understand your point. The ** operator is not symmetric (2**3 != 3**2). Precedence can be emulated by placing parentheses. So if you put in parentheses in different ways then the results will in general be different.
    – nikow
    Commented May 14, 2009 at 8:57
3

Evaluating right-to-left, let's look at the steps Python is going through to get these answers:

2**2
4

2**(2**2)
2**(4)
16

2**(2**(2**2))
2**(2**(4))
2**(16)
65536

2**(2**(2**(2**2)))
2**(2**(2**(4)))
2**(2**(16))
2**(65536)
2.0035299304068464649790723515603e+19728

Not the answer you're looking for? Browse other questions tagged or ask your own question.