tags:

views:

216

answers:

5

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)

+16  A: 

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

2**(4) = 16

IN[3] = 2**2**2**2 = 2**2**(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

AlbertoPL
+7  A: 

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)))
Martin Cote
+3  A: 

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
HanClinto
+3  A: 

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
Smashery
+4  A: 

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.

nikow
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.
Salim Fadhley
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