Search code examples
pythonoptimizationconvergence

Extracting the converged? bool of scipy.optimize.newton() result


I'm trying to find the minimum root of a function using scipy.optimize.newton(). The function I'm using is very complicated, and as a result I decided to have a set number of iterations and to keep the final answer even if the precision asked is not respected. As such, I would like to know when convergence happened and when it didn't, in one single bool variable.

The problem I'm running in is that newton() returns a 2 dimensional array with the root result as the first value, and the second value is an object with several values, of which I can't seem to extract the converged one.

I tried to look only at the second value of the newton return function. This is my code:

from scipy.optimize import newton

def function(x):
    return x**2-1

def fprime(x):
    return 2*x

x0=5

test = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)


print(test[1])

Which gives

      converged: False
           flag: 'convergence error'
 function_calls: 7
     iterations: 5
           root: 1.0103336911991998

and what I would like is just one variable with 'False' in it (for this example)


Solution

  • In your way of calling scipy.optimize.newton, newton returns a 2-element tuple, and the first element is the root, the second is a RootResults object. If you want to get the converged attribute of the RootResults object, you just need to use dot notation, some_obj.attribute.

    root, r = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)
    converged_flag = r.converged
    print(converged_flag)