I have the following code in Python
z = [[complex(x,y) for x in range(1000)]for y in range(1000)]
nexp = np.frompyfunc(cmath.exp,1,1)
nexp(z)
I have OverflowError: math range error.
Is there any way to find which elements of array rises error and handle it? I mean if I simply iterate through array I could make it that way
for x in range(1000):
for y in range(1000):
try:
z[x,y] = cmath.exp(z[x,y])
except:
z[x,y] = 0
Why don't you use numpy types and methods instead of complex
and cmath
?
Demo:
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
this yields:
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])
all infinite elements:
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])
index of the first infinite element:
In [306]: np.isinf(y).argmax()
Out[306]: 9