Skip to Content
ModulesSciPy TutorialRoot Finding & Optimization

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 f(x)=0f(x) = 0:

Always use brentq when you can bracket the root with f(a)⋅f(b)<0f(a) \cdot f(b) < 0. 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 x⋅ex=1x \cdot e^x = 1 (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:

MethodGradientsBoundsConstraintsUse Case
'BFGS'Quasi-NewtonNoNoSmooth unconstrained problems
'L-BFGS-B'Quasi-NewtonYesNoLarge-scale bounded optimization
'Nelder-Mead'Derivative-freeOptionalNoRugged, noisy, or non-differentiable functions
'SLSQP'Sequential Least SquaresYesYesGeneral engineering constrained optimization

Example: Constrained Tank Optimization

Design a cylindrical tank of fixed volume V=1.0 dm3V = 1.0\text{ dm}^3 with minimal surface area A=2πr2+2πrhA = 2\pi r^2 + 2\pi r h. Analytically, the optimum occurs at h=2r  ⟹  r=(V/2π)1/3≈0.5419 dmh = 2r \implies r = (V / 2\pi)^{1/3} \approx 0.5419\text{ dm}:


Example

Output:



3. Linear Programming (linprog)

scipy.optimize.linprog solves problems of the form min⁡cTx\min \mathbf{c}^T \mathbf{x} subject to Aubx≤bubA_{ub} \mathbf{x} \le \mathbf{b}_{ub}.

Suppose a machine shop produces two items:

  • Profit: Item 1 = $40, Item 2 = $30.
  • Constraints: Machine hours ≤12\le 12 (x1+x2≤12x_1 + x_2 \le 12), Raw material ≤16 kg\le 16\text{ kg} (2x1+x2≤162x_1 + x_2 \le 16). We maximize profit (minimize −40x1−30x2-40x_1 - 30x_2):

Example

Output:



4. Nonlinear Curve Fitting (curve_fit)

scipy.optimize.curve_fit estimates parameters θ\boldsymbol{\theta} for non-linear regression y=f(x;θ)y = f(x; \boldsymbol{\theta}) 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 f(x)=(x−3.5)2+1.25f(x) = (x - 3.5)^2 + 1.25 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}")

PygroundTry It Out

Minimize f(x) = (x - 3.5)^2 + 1.25 using minimize.

Output:

Last updated on