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
bracketneeds a sign change between the two ends.fprimelets Newton's method converge faster.least_squaresminimizes a vector of residuals.
Keywords and builtins used here
asdeflambdaprintreturnroundsystem
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.
Step 4 of 4 in Optimization, step 13 of 23 in Scientific computing with SciPy.