Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Solving a small nonlinear system with NumJac

A tiny worked example of using pymrm.NumJac to get a numerical Jacobian for a hand-written residual, and feeding the pair (g, jac) to a general-purpose solver. The system is

a x02+b x12−1=0,x0−x1=0,a\,x_0^2 + b\,x_1^2 - 1 = 0, \qquad x_0 - x_1 = 0,

solved once with scipy.optimize.root and once with pymrm.newton, to compare the two solvers on the same residual and Jacobian.

Imports

Residual, Jacobian, and initial guess

numjac differentiates fun numerically; wrapper_fun adapts the (g, jac) pair to the dense Jacobian that scipy.optimize.root expects.

Solve with SciPy and with pymrm.newton

Solution SciPy root:
  message: The solution converged.
 success: True
  status: 1
     fun: [ 2.220e-16  0.000e+00]
       x: [ 4.472e-01  4.472e-01]
  method: hybr
    nfev: 8
    njev: 1
    fjac: [[-8.769e-01 -4.807e-01]
           [ 4.807e-01 -8.769e-01]]
       r: [-2.080e+00 -1.841e+00  2.150e+00]
     qtf: [-3.263e-10  1.789e-10]

Solution pymrm newton:
         message: Converged
        success: True
         status: 0
            fun: [ 4.155e-10  0.000e+00]
              x: [ 4.472e-01  4.472e-01]
            nit: 4
           nfev: 4
          nfact: 4
      step_norm: 9.291678019311268e-11
 backward_error: 6.92560789111425e-11
        history: [{'step_norm': 0.04999995000115609, 'damping': 1.0, 'theta': nan, 'clipped': 0}, {'step_norm': 0.002777824381426678, 'damping': 1.0, 'theta': nan, 'clipped': 0}, {'step_norm': 8.63002454241893e-06, 'damping': 1.0, 'theta': nan, 'clipped': 0}, {'step_norm': 9.291678019311268e-11, 'damping': 1.0, 'theta': nan, 'clipped': 0}]

Checking the result

With x0=x1x_0=x_1 the first equation gives a closed form, x0=x1=1/a+bx_0=x_1=1/\sqrt{a+b}. Comparing both numerical solutions against it catches a wrong Jacobian, a solver that stopped short of convergence, or the wrong root of the (otherwise symmetric) system.

exact               x0=x1=0.447213595500
SciPy root          x0=0.447213595500, x1=0.447213595500, max abs error 5.551e-17
pymrm newton        x0=0.447213595500, x1=0.447213595500, max abs error 1.110e-16