Handling OverflowError: math range error in Python with NumPy
Handling OverflowError: math range error in Python with NumPy
我在Python
中有以下代码
z = [[complex(x,y) for x in range(1000)]for y in range(1000)]
nexp = np.frompyfunc(cmath.exp,1,1)
nexp(z)
我有 OverflowError:数学范围错误。
有没有办法找到数组的哪些元素出现错误并处理?
我的意思是,如果我只是简单地遍历数组,我就可以做到这一点
for x in range(1000):
for y in range(1000):
try:
z[x,y] = cmath.exp(z[x,y])
except:
z[x,y] = 0
为什么不使用 numpy 类型和方法来代替 complex
和 cmath
?
演示:
In [302]: x = np.arange(701, 720) + 1j*np.arange(701, 720)
In [303]: y = np.exp(x)
~\Anaconda3_5.0\envs\py36\Scripts\ipython3:1: RuntimeWarning: overflow encountered in exp
这产生:
In [304]: y
Out[304]:
array([ -2.51188899e+304 -1.13634915e+304j, -1.08996190e+304 -7.41453166e+304j, 1.53588478e+305 -1.33828078e+305j, 5.31686829e+305 +1.5
4758929e+305j, 4.26896569e+305 +1.44345018e+306j,
-2.67470300e+306 +3.09645066e+306j, -1.10110029e+307 -1.57025773e+306j, -1.25800559e+307 -2.74923036e+307j, 4.44084142e+307 -6.9
1528370e+307j, inf +1.34684655e+304j,
inf +infj, -inf +infj, -inf +infj, -inf
-infj, inf -infj,
inf -infj, inf +infj, -inf +infj, -inf
+infj])
所有无限元素:
In [305]: y[np.isinf(y)]
Out[305]:
array([ inf +1.34684655e+304j, inf +infj, -inf +infj, -inf +infj, -inf -infj, inf
-infj, inf -infj, inf +infj,
-inf +infj, -inf +infj])
第一个无限元的索引:
In [306]: np.isinf(y).argmax()
Out[306]: 9
我在Python
中有以下代码z = [[complex(x,y) for x in range(1000)]for y in range(1000)]
nexp = np.frompyfunc(cmath.exp,1,1)
nexp(z)
我有 OverflowError:数学范围错误。
有没有办法找到数组的哪些元素出现错误并处理? 我的意思是,如果我只是简单地遍历数组,我就可以做到这一点
for x in range(1000):
for y in range(1000):
try:
z[x,y] = cmath.exp(z[x,y])
except:
z[x,y] = 0
为什么不使用 numpy 类型和方法来代替 complex
和 cmath
?
演示:
In [302]: x = np.arange(701, 720) + 1j*np.arange(701, 720)
In [303]: y = np.exp(x)
~\Anaconda3_5.0\envs\py36\Scripts\ipython3:1: RuntimeWarning: overflow encountered in exp
这产生:
In [304]: y
Out[304]:
array([ -2.51188899e+304 -1.13634915e+304j, -1.08996190e+304 -7.41453166e+304j, 1.53588478e+305 -1.33828078e+305j, 5.31686829e+305 +1.5
4758929e+305j, 4.26896569e+305 +1.44345018e+306j,
-2.67470300e+306 +3.09645066e+306j, -1.10110029e+307 -1.57025773e+306j, -1.25800559e+307 -2.74923036e+307j, 4.44084142e+307 -6.9
1528370e+307j, inf +1.34684655e+304j,
inf +infj, -inf +infj, -inf +infj, -inf
-infj, inf -infj,
inf -infj, inf +infj, -inf +infj, -inf
+infj])
所有无限元素:
In [305]: y[np.isinf(y)]
Out[305]:
array([ inf +1.34684655e+304j, inf +infj, -inf +infj, -inf +infj, -inf -infj, inf
-infj, inf -infj, inf +infj,
-inf +infj, -inf +infj])
第一个无限元的索引:
In [306]: np.isinf(y).argmax()
Out[306]: 9