Root Finding & Optimization (scipy.optimize)
Optimization and root finding answer the questions: “Where does my system reach equilibrium?” and “What parameter values give the lowest cost or smallest error?“
1. 1D Root Finding: brentq vs newton
When you have a scalar function :
brentq (Bracketed Root)
Always use brentq when you can bracket the root with . It combines the speed of inverse quadratic interpolation with the guaranteed convergence of bisection:
from scipy.optimize import brentq
root = brentq(f, a, b)Example: Solving Transcendental Roots
Solve (the Omega constant, analytical solution via Lambert W function):
Example
Output:
2. Multivariable Minimization (minimize)
scipy.optimize.minimize handles both unconstrained and constrained optimization problems:
| Method | Gradients | Bounds | Constraints | Use Case |
|---|---|---|---|---|
'BFGS' | Quasi-Newton | No | No | Smooth unconstrained problems |
'L-BFGS-B' | Quasi-Newton | Yes | No | Large-scale bounded optimization |
'Nelder-Mead' | Derivative-free | Optional | No | Rugged, noisy, or non-differentiable functions |
'SLSQP' | Sequential Least Squares | Yes | Yes | General engineering constrained optimization |
Example: Constrained Tank Optimization
Design a cylindrical tank of fixed volume with minimal surface area . Analytically, the optimum occurs at :
Example
Output:
3. Linear Programming (linprog)
scipy.optimize.linprog solves problems of the form subject to .
Suppose a machine shop produces two items:
- Profit: Item 1 = $40, Item 2 = $30.
- Constraints: Machine hours (), Raw material (). We maximize profit (minimize ):
Example
Output:
4. Nonlinear Curve Fitting (curve_fit)
scipy.optimize.curve_fit estimates parameters for non-linear regression via Levenberg-Marquardt or Trust Region Reflective algorithms, returning both parameter estimates and the parameter covariance matrix pcov:
Example
Output:
5. Try It Yourself
Problem: Minimize a Quadratic Function
Find the minimum of using scipy.optimize.minimize.
Show solution
from scipy.optimize import minimize
def f(x):
return (x[0] - 3.5)**2 + 1.25
res = minimize(f, x0=[0.0], method='BFGS')
print(f"Optimal x: {res.x[0]:.4f}")
print(f"Minimum f(x): {res.fun:.4f}")