newton_ndim#

rateslib.solver.newton_ndim(f, g0, max_iter=50, func_tol=1e-14, conv_tol=1e-09, args=(), pre_args=(), final_args=(), raise_on_fail=True)#

Use the Newton-Raphson algorithm to determine a function root searching many variables.

Solves the n root equations \(f_i(g_1, \hdots, g_n; s_k)=0\) for each \(g_j\).

Parameters:
  • f (callable) – The function, f, to find the root of. Of the signature: f([g_1, .., g_n], *args). Must return a tuple where the second value is the Jacobian of f with respect to g.

  • g0 (Sequence of DualTypes) – Initial guess of the root values. Should be reasonable to avoid failure.

  • max_iter (int) – The maximum number of iterations to try before exiting.

  • func_tol (float, optional) – The absolute function tolerance to reach before exiting.

  • conv_tol (float, optional) – The convergence tolerance for subsequent iterations of g.

  • args (tuple of float, Dual or Dual2) – Additional arguments passed to f.

  • pre_args (tuple) – Additional arguments passed to f only in the float solve section of the algorithm. Functions are called with the signature f(g, *(*args[as float], *pre_args)).

  • final_args (tuple of float, Dual, Dual2) – Additional arguments passed to f in the final iteration of the algorithm to capture AD sensitivities. Functions are called with the signature f(g, *(*args, *final_args)).

  • raise_on_fail (bool, optional) – If False will return a solver result dict with state and message indicating failure.

Return type:

dict

Examples

Iteratively solve the equation system:

  • \(f_0(\mathbf{g}, s) = g_1^2 + g_2^2 + s = 0\).

  • \(f_1(\mathbf{g}, s) = g_1^2 - 2g_2^2 + s = 0\).

In [1]: from rateslib.solver import newton_ndim

In [2]: def f(g, s):
   ...:     f0 = g[0] ** 2 + g[1] ** 2 + s
   ...:     f1 = g[0] ** 2 - 2 * g[1]**2 - s
   ...:     f00 = 2 * g[0]
   ...:     f01 = 2 * g[1]
   ...:     f10 = 2 * g[0]
   ...:     f11 = -4 * g[1]
   ...:     return [f0, f1], [[f00, f01], [f10, f11]]
   ...: 

In [3]: s = Dual(-2.0, ["s"], [])

In [4]: newton_ndim(f, g0=[1.0, 1.0], args=(s,))
Out[4]: 
{'status': 'SUCCESS',
 'state': 2,
 'g': array([<Dual: 0.816497, (s), [-0.2]>, <Dual: 1.154701, (s), [-0.3]>],
       dtype=object),
 'iterations': 6,
 'time': 0.0005278587341308594}