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)
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
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)))
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With