2

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)

  • `scipy.optimize.newton` finds the root of a function, that is, `x0` where `f(x0) = 0`. But you said you wanted a minimum of the function. Could you clarify this? – liginity Jun 26 '23 at 08:56
  • sorry, yes, I'm trying to minimise a function by finding the root of a related function. I'll edit. – Reflets de Lune Jun 26 '23 at 09:14

1 Answers1

0

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)
liginity
  • 311
  • 3
  • 7