root function
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 inputx0: initial guessmethod: algorithm, RootMethod.lm by defaultjacobian: function that returns the Jacobian matrixJ[i][j] = df_i/dx_j. When null, it is approximated by forward differencesftol: the root is accepted whenmax(|f(x)|) <= ftolxtol: the solver stops when the step is smaller thanxtol * (1 + max(|x|))maxIter: maximum number of iterations
Returns
- OptimizeResult with the solution and OptimizeResult.success
References
- "scipy.optimize.root". https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html. Retrieved 2026-10-13.
- J. Nocedal and S. J. Wright, "Numerical Optimization", 2nd ed., Springer, 2006, chapter 11.
- 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);
}
}