Search code examples
pythonscipy-optimizeconvergence

How can I handle divergence failure manually when using optimize.newton in SciPy?


I'm using newton optimize from SciPy to solve an equation and depending on the initial guess sometimes the solution does not converge and crashes.

x = optimize.newton(fun,1/1000)

Would it be possible to print a message instead of the python crash message to say that convergence failed or retry optimization with different initial values?


Solution

  • From the documentation:

    disp: bool, optional

    If True, raise a RuntimeError if the algorithm didn’t converge, with the error message containing the number of iterations and current function value. Otherwise the convergence status is recorded in a RootResults return object. Ignored if x0 is not scalar. Note: this has little to do with displaying, however the disp keyword cannot be renamed for backwards compatibility.

    You should set disp to False, because it is enabled by default:

    optimize.newton(fun, 1/1000, disp=False)
    

    Your result and other information will be in a RootResults object.