Search code examples
numpydivide-by-zerominimization

Minimization leastsq with division by zero


I would like to apply a minimization on a function which contains division and some trigonometric function as you can see below with a piece of code. But an error appears with a divide by zero :

RuntimeWarning: divide by zero encountered in divide launch_new_instance()

Lx=2592.
Ly=1936.

YA, XA = np.mgrid[0:Ly, 0:Lx]

XAvect=np.reshape(XA,(Lx*Ly))
YAvect=np.reshape(YA,(Lx*Ly))

#Initialization
x0 = 200.
y0 = 200.
KI = 100000.
T = 20.
A1 = 50.
A2 = 50.


def residual_V2west(vars, XA, YA, donnees):
    KI = vars[0]
    A1 = vars[1]
    A2 = vars[2]
    x0 = vars[3]
    y0 = vars[4]
    modeleV2 = KI/(G)*np.sqrt(np.sqrt((XA-x0)**2 + (YA-y0)**2)/(2*np.pi))*np.sin((np.arctan(((YA-y0)/(XA-x0))))/2)*(Kappa + 1 - 2*np.cos(np.arctan(((YA-y0)/(XA-x0)))/2)**2) + \
    A1*np.sqrt((XA-x0)**2+(YA-y0)**2)*np.cos(np.arctan((YA-y0)/(XA-x0))) + A2 
    return (donnees-modeleV2)

from scipy.optimize import leastsq
vars = [KI, A1, A2, x0, y0]
out_V_west = sco.leastsq(residual_V2west, vars, args=(XAvect, YAvect, Vmvect),epsfcn=0.01)
print out_V_west

Solution

  • You could try to avoid the division by zero by defining the denominator to be a small number instead of zero:

    XAmx0 = XA-x0 if abs(XAmx0) < 1e-12: XAmx0 = 1e-12

    And then divide by XAmx0 instead of XA-x0

    This regularizes your expression in the residual function and does not affect your result (if the denominator in the optimal solution is on the order of 1e-12, you are likely to get problems with numerical accurraccy anyway)