I want to replace the divisor with a very small number if it equals to 0. I am doing an operation which is like:
A = pow(X,2)/(q - P)
It computes these values and stores them in an array (for looped). However, at certain places q - P = 0
, which throws a runtime error. I know that there is a work around, I do not want that. How can I set q - P to a very small number in case q - P = 0
for a particular iteration.
I would recommend to use a try except block and set A
to a different value if a ZeroDivisionError
error occurs:
try:
A = (pow(X,2))/(q - P))
except ZeroDivisionError:
A = 99999999999 #big nuber because devision by a small number
# you can also set A to infinity with `A = np.inf`
If thats not an option for you (e.g. you really want to change q or P and not only A) you can simply add a small number to q or P
if q == P:
q+= 0.00000000000001 # or P+=small_number or q-=small_number or P-=small_number