Specialize complex power for integer/real exponents
@skirpichev 已经在做这个了。
开始于 2025年8月14日。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Proposal:
With #69639 complex arithmetic in Python was extended to support C-like mixed-more rules, where one operand is a float or an int. However, this doesn't affect exponentiation.
Currently we have, for example:
>>> import cmath
>>> z = complex('inf')
>>> z**0.5
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
z**0.5
~^^~~~
OverflowError: complex exponentiation
>>> cmath.sqrt(z)
(inf+0j)
>>> z**2
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
z**2
~^^~
OverflowError: complex exponentiation
which is just meaningless. Note also, that plain multiplication is not too much better in the last case:
>>> z*z
(inf+nanj)
What we actually want here is exp(log(z)*real_exponent):
>>> import cmath, math
>>> def mypow(b, e):
... if isinstance(b, (float, int)) and b > 0:
... if isinstance(e, (float, int)):
... return math.exp(e*math.log(b))
... return cmath.exp(e*math.log(b))
... return cmath.exp(e*cmath.log(b))
...
>>> mypow(z, 2)
(inf+0j)
>>> mypow(z+123j, 2)
(inf+0j)
This works as expected for real exponents and/or positive bases due to special mixed-mode rules in complex arithmetic (this time - in multiplication).
Special rules for exponentiation will be useful for implementation of complex functions, using known analytic identities. For example:
>>> cmath.asinh(z)
(inf+0j)
>>> myasinh_bad = lambda z: cmath.log(z + cmath.sqrt(1 + z**2))
>>> myasinh_bad(z)
Traceback (most recent call last):
File "<python-input-11>", line 1, in <module>
myasinh_bad(z)
~~~~~~~~~~~^^^
File "<python-input-10>", line 1, in <lambda>
myasinh_bad = lambda z: cmath.log(z + cmath.sqrt(1 + z**2))
~^^~
OverflowError: complex exponentiation
>>> myasinh_bad2 = lambda z: cmath.log(z + cmath.sqrt(1 + z*z))
>>> myasinh_bad2(z)
(inf+nanj)
>>> myasinh_good = lambda z: cmath.log(z + cmath.sqrt(1 + mypow(z, 2)))
>>> myasinh_good(z)
(inf+0j)
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
评估
这个 Issue 还没有评估数据。