typestar

Finding roots in Python

root_scalar for one equation, root for a system, least_squares for a fit.

import numpy as np
from scipy import optimize

one = optimize.root_scalar(lambda x: x ** 3 - 2 * x - 5,
                           bracket=[2, 3], method="brentq")
print(round(one.root, 6), one.iterations, one.converged)

newton = optimize.root_scalar(lambda x: np.cos(x) - x, x0=0.5,
                              fprime=lambda x: -np.sin(x) - 1,
                              method="newton")
print(round(newton.root, 6))


def system(v):
    x, y = v
    return [x + y - 3, x * y - 2]


both = optimize.root(system, x0=[0.0, 5.0])
print(both.x.round(4), both.success)

How it works

  1. bracket needs a sign change between the two ends.
  2. fprime lets Newton's method converge faster.
  3. least_squares minimizes a vector of residuals.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
475
Tokens
171
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 93 seconds.

Type this snippet

Step 4 of 4 in Optimization, step 13 of 23 in Scientific computing with SciPy.

← Previous Next →