Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is exponentiation applied right to left?

I am reading an Intro to Python textbook and came across this line:

Operators on the same row have equal precedence and are applied left to right, except for exponentiation, which is applied right to left.

I understand most of this, but I do not understand why they say exponentiation is applied right to left. They do not provide any examples either. Also, am I allowed to ask general questions like this, or are only problem solving questions preferred?

like image 486
elitecheese1337 Avatar asked Nov 22 '17 08:11

elitecheese1337


2 Answers

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.

like image 150
Martijn Pieters Avatar answered Oct 07 '22 18:10

Martijn Pieters


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!
like image 39
Vivek Kalyanarangan Avatar answered Oct 07 '22 19:10

Vivek Kalyanarangan