Unable to understand operator behavior **
I suddenly stumbled upon this, I can't figure out why this is happening!
On the python command line, using operator **
with 3's and so on as shown below, giving incorrect result. those.
>>> 2**2**2
16
>>> 3**3**3
7625597484987L
>>> 4**4**4
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096L
Then I thought I should use parentheses, so I used it and it gives the correct result.
>>>(3**3)**3
19683
BUT the operator //
supports and gives correct results in this type of operation, i.e.
>>> 4//4//4
0
>>> 40//4//6
1
Please help me understand.
source to share
**
is right-associative. Mathematically, this makes sense: 3 3 3 equals 3 27 and not 27 3 .
The documentation claims to be right-associative:
In an incomparable sequence of power and unary operators, the operators are evaluated from right to left.
source to share
As the docs say:
Operators in the same group of fields from left to right (except for comparisons ... and exponentials, which are grouped from right to left).
In other words, it **
is right-associative, and //
(like all other operators, except comparisons), it is left-associative.
Elsewhere there is a whole section on Power Operator which, after providing a rule (which is irrelevant here) about how power and Unary Operators interact, explains that:
[I] n non-spherical sequence of power and unary operators, operators are evaluated from right to left ...
This is indeed how most programming languages do it.
Exponentiation is not written with symmetric operator syntax in mathematics, so there is no reason why it should have the same associativity by default. And right-associative exponentiation is much less useful, because it (2**3)**4
is exactly the same as and 2**(3*4)
, while there is nothing obvious that it is the same that 2**(3**4)
.
source to share
When you do something like 4**4**4
you should use parentheses to make your intent explicit. The parser will resolve the ambiguity as @cHao pointed out, but this is confusing others. You must use (4**4)**4
or 4**(4**4)
. Explicit is better here than implicit, as accepting credentials is not exactly the exact work we see all the time.
source to share