Why is exponentiation applied right to left?

♀尐吖头ヾ 提交于 2019-11-28 14:09:27

The ** operator follows normal mathematical conventions; it is right-associative:

In the usual computer science jargon, exponentiation in mathematics is right-associative, which means that xyz should be read as x(yz), not (xy)z. In expositions of the BODMAS rules that are careful enough to address this question, the rule is to evaluate the top exponent first.

and from Wikipedia on the Order of Operations:

If exponentiation is indicated by stacked symbols, the usual rule is to work from the top down, because exponention is right-associative in mathematics.

So 2 ** 3 ** 4 is calculated as 2 ** (3 ** 4) (== 2417851639229258349412352) not (2 ** 3) ** 4 (== 4096).

This is pretty universal across programming languages; it is called right-associativity, although there are exceptions, with Excel and MATLAB being the most notable.

from http://docs.python.org/reference/expressions.html

Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).

>>> 2 ** 2 ** 2
16
>>> 2 ** 2 ** 2 ** 2
65536
>>> (2 ** 2 ** 2) ** 2
256

For the middle case 2 ** 2 ** 2 ** 2, this are the intermediate steps -

  1. broken down to 2 ** (2 ** (2 ** 2))
  2. 2 ** (2 ** (4)) # progressing right to left
  3. 2 ** (16) # this is 2 to the power 16 which finally evals to 65536 Hope that helps!

This explanation seems quite clear to me. Let me show you an example that might enlighten this :

print 2 ** 2 ** 3 # prints 256

If you would read this from left to right, you would first do 2 ** 2, which would result in 4, and then 4 ** 3, which would give us 64. It seems we have a wrong answer. :)

However, from right to left... You would first do 2 ** 3, which would be 8, and then, 2 ** 8, giving us 256 !

I hope I was able to enlighten this point for you. :)

EDIT : Martijn Pieters answered more accurately to your question, sorry. I forgot to say it was mathematical conventions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!