Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange python behaviour

Tags:

python

ipython

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)

like image 968
fforw Avatar asked May 12 '09 15:05

fforw


5 Answers

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

like image 155
AlbertoPL Avatar answered Nov 17 '22 03:11

AlbertoPL


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)))
like image 7
Martin Cote Avatar answered Nov 17 '22 02:11

Martin Cote


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
like image 4
HanClinto Avatar answered Nov 17 '22 03:11

HanClinto


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.

like image 4
nikow Avatar answered Nov 17 '22 02:11

nikow


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
like image 3
Smashery Avatar answered Nov 17 '22 02:11

Smashery