Why is exponentiation applied right to left? Python
Why is exponentiation applied right to left?
回答1
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.
回答2
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 -
- broken down to
2 ** (2 ** (2 ** 2))
2 ** (2 ** (4)) # progressing right to left
2 ** (16) # this is 2 to the power 16
which finally evals to65536
Hope that helps!
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-09-24 Anti forgery token is meant for user "" but the current user is "username"
2021-09-24 Asp.net Mvc AntiForgeryToken全局处理
2021-09-24 Does it make sense to put antiforgerytoken in _Layout.cshtml?
2021-09-24 jQuery .val()
2021-09-24 Understanding multiple anti-forgery tokens in ASP.NET MVC
2021-09-24 Duplicate Files Search & Link
2021-09-24 The source contains no DataRows