root function

OptimizeResult root(
  1. Array f(
    1. Array
    ),
  2. Array x0, {
  3. RootMethod method = RootMethod.lm,
  4. Array2d jacobian(
    1. Array
    )?,
  5. double ftol = 1e-10,
  6. double xtol = 1e-12,
  7. int maxIter = 200,
})

Find a root of the vector function f (from R^n to R^n) starting at x0, like scipy.optimize.root.

  • f : function that returns an Array with the same length as its input
  • x0 : initial guess
  • method : algorithm, RootMethod.lm by default
  • jacobian : function that returns the Jacobian matrix J[i][j] = df_i/dx_j. When null, it is approximated by forward differences
  • ftol : the root is accepted when max(|f(x)|) <= ftol
  • xtol : the solver stops when the step is smaller than xtol * (1 + max(|x|))
  • maxIter : maximum number of iterations

Returns

References

  1. "scipy.optimize.root". https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html. Retrieved 2026-10-13.
  2. J. Nocedal and S. J. Wright, "Numerical Optimization", 2nd ed., Springer, 2006, chapter 11.
  3. C. G. Broyden, "A class of methods for solving nonlinear simultaneous equations", Mathematics of Computation 19 (1965), 577-593.

Examples

// x^2 + y^2 = 4 and x = y
var r = root((v) => Array([v[0] * v[0] + v[1] * v[1] - 4, v[0] - v[1]]),
    Array([1.0, 0.5]));

print(r.x);

/* output:
Array([1.4142135623730978, 1.4142135623730978])
*/

Implementation

OptimizeResult root(
  Array Function(Array) f,
  Array x0, {
  RootMethod method = RootMethod.lm,
  Array2d Function(Array)? jacobian,
  double ftol = 1e-10,
  double xtol = 1e-12,
  int maxIter = 200,
}) {
  if (x0.isEmpty) {
    throw FormatException('x0 must not be empty');
  }
  if (maxIter < 1) {
    throw FormatException('maxIter must be >= 1, got $maxIter');
  }
  var solver = _Solver(f, jacobian, ftol, xtol, maxIter);
  switch (method) {
    case RootMethod.lm:
      return solver.levenbergMarquardt(x0);
    case RootMethod.newton:
      return solver.newton(x0);
    case RootMethod.broyden1:
      return solver.broyden(x0);
  }
}