在Python的复数幂乘什么情况下抛出一个OverflowError? [英] In what cases does Python complex exponentiation throw an OverflowError?

查看:1387
本文介绍了在Python的复数幂乘什么情况下抛出一个OverflowError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 >>>我试图找出这里的模式: 1e300 ** 2 
OverflowError:(34,'Result too large')
>>> 1e300j ** 2
OverflowError:complex exponentiation
>>> (1e300 + 1j)** 2
OverflowError:复数指数
>>> (1e300 + 1e300j)** 2
(nan + nanj)

理论上不仅没有说明,而且在实践中也是怪异的!这是什么解释?

解决方案

source ,表示Python只在计算结束时检查溢出。此外,还有一个小整数指数的特殊情况,它使用取平方的指数运算,这涉及到复数乘法。

  r.real = a .real * b.real  -  a.imag * b.imag; 
r.imag = a.real * b.imag + a.imag * b.real;

这是复数乘法的公式。请注意以下几点:

  a.real * b.real  -  a.imag * b.imag 
a
b

c>非常大,这就变成了浮点无穷大减去浮点无穷大,即 nan nan 结果会传播,经过几次操作后,结果是(nan + nanj) Py_ADJUST_ERANGE2 只设置 errno 如果它看到一个无穷大,所以它忽略了溢出并继续前进。



总之,Python只检查溢出的最终结果,而不检查中间值,这会导致它错过中间的溢出,因为它们都是 / code> s结束。引发 OverflowError 的表达式是这样做的,因为它们从不尝试减去无穷大,所以错误在最后被发现。这看起来不像是一个故意的设计决定;你可以通过改变溢出检查的方式来修复它。


I’m trying to figure out the pattern here:

>>> 1e300 ** 2
OverflowError: (34, 'Result too large')
>>> 1e300j ** 2
OverflowError: complex exponentiation
>>> (1e300 + 1j) ** 2
OverflowError: complex exponentiation
>>> (1e300 + 1e300j) ** 2
(nan+nanj)

The behavior seems to be not only unspecified in theory, but also weird in practice! What explains this?

解决方案

A look at the source for complex exponentiation shows that Python only checks for overflow at the end of the computation. Also, there's a special case for small integer exponents that uses exponentiation by squaring, which involves complex multiplication.

r.real = a.real*b.real - a.imag*b.imag;
r.imag = a.real*b.imag + a.imag*b.real;

This is the formula for complex multiplication. Note the following:

a.real*b.real - a.imag*b.imag

When a and b are very large, this becomes floating-point infinity minus floating-point infinity, which is nan. The nan results propagate, and after a few operations, the result is (nan+nanj). Py_ADJUST_ERANGE2 only sets errno if it sees an infinity, so it misses the overflow and goes on its way.

In summary, Python only checks the end result for overflow, not intermediate values, and this causes it to miss the overflow in the middle because it's all nans by the end. The expressions that do raise OverflowError do so because they never try to subtract infinities, so the error is spotted by the end. It doesn't look like a deliberate design decision; you could fix it by changing the way the overflow check works.

这篇关于在Python的复数幂乘什么情况下抛出一个OverflowError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆