I would like to avoid ZeroDivisionError: complex division by zero
in my calculation, getting nan
at that exception.
Let me lay out my question with a simple example:
from numpy import *
from cmath import *
def f(x) :
x = float_(x)
return 1./(1.-x)
def g(x) :
x = float_(x)
return sqrt(-1.)/(1.-x)
f(1.) # This gives 'inf'.
g(1.) # This gives 'ZeroDivisionError: complex division by zero'.
It is my intention to get g(1.) = nan
, or at least anything but an error that interrupts the calculation.
First question: how can I do it?
Importantly, I would not like to modify the code inside the functions (for example, inserting conditions for exceptions, as is done in this answer), but rather keep it in its current form (or even deleting the x = float_(x)
line if possible, as I mention below).
The reason is that I am working with a long code with dozens of functions: I would like them all to avoid ZeroDivisionError
without the need of making lots of changes.
I was forced to insert x = float_(x)
to avoid a ZeroDivisionError
in f(1.)
.
Second question: would there be a way of suppressing this line but still get f(1.) = inf
without modifying at all the code defining f
?
EDIT:
I have realized that using cmath
(from cmath import *
) is responsible for the error.
Without it, I get g(1.) = nan
, which is what I want.
However, I need it in my code.
So now the first question turns into the following: how can I avoid "complex division by zero" when using cmath
?
EDIT 2:
After reading the answers, I have made some changes and I simplify the question, getting closer to the point:
import numpy as np
import cmath as cm
def g(x) :
x = np.float_(x)
return cm.sqrt(x+1.)/(x-1.) # I want 'g' to be defined in R-{1},
# so I have to use 'cm.sqrt'.
print 'g(1.) =', g(1.) # This gives 'ZeroDivisionError:
# complex division by zero'.
Question: how can I avoid the ZeroDivisionError
not modifying the code of my function g
?