3

I'm using scipy to find the root(s) of a vector function and I want to have it ignore non-convergence. Basically, I set the function tolerance and maxiter, but if it doesn't converge within those constraints I don't really care. I'm using scipy.optimize.newton_krylov and setting the arguments maxiter and f_tol. I just don't want non-convergence to raise an exception.

EDIT: I was a little unclear. I want to get the solution from the optimizer even if it doesn't "converge." I can handle this with a try/except, but this is slow. It would require re-running the optimizer, which is computationally expensive. I know (for my problem) a good solution will be found after maxiter iterations, but a good enough solution can often be found if |F| < f_tol, which can cut down on the total number of iterations by a lot and save lots of time.

Lothar
  • 63
  • 5
  • 1
    Possible duplicate: http://stackoverflow.com/questions/730764/try-except-in-python-how-to-properly-ignore-exceptions – Dair Jun 04 '14 at 01:56
  • 1
    What *should* happen, if not an exception? My guess is that you'll want to catch the exception and do whatever constitutes "ignoring it" for your particular situation. – user2357112 Jun 04 '14 at 01:56
  • @anon : It's not a case of the try/except handling. To handle the exception I'd have to re-run the optimizer, which is computationally expensive. – Lothar Jun 04 '14 at 23:18

1 Answers1

4

The NoConvergence exception that is thrown on non-convergence contains the latest iteration as its argument. So you can do

try:
    x = newton_krylov(F, x0)
    converged = True
except NoConvergence as e:
    x = e.args[0]
    converged = False
Dominic Else
  • 141
  • 4