Skip to main content
Albero Academy

Optimization & Root Finding

Find the minimum of a function, fit a curve to data, and solve equations numerically with scipy.optimize.

Chapter 3SciPy15 min readBeginner friendly
  • #SciPy
  • #Optimization
  • #Curve Fitting

Optimisation — finding the input that makes a function smallest (or largest) — is everywhere: fitting a model, minimising cost, maximising revenue. scipy.optimize gives you robust numerical solvers so you don't hand-roll calculus.

Why optimisation?

Machine learning is optimisation under the hood — "find the parameters that minimise the error". Beyond ML, you'll optimise pricing, schedules, resource allocation. The pattern is always: define a function to minimise, hand it to a solver.

Minimising a function

find the minimum
from scipy import optimize
# Minimise f(x) = (x - 3)^2 + 1 → minimum at x = 3
def f(x):
return (x - 3)**2 + 1
result = optimize.minimize(f, x0=0) # x0 = starting guess
print(result.x) # ≈ [3.0] the minimising input
print(result.fun) # ≈ 1.0 the minimum value

Curve fitting

curve_fit finds the parameters of a model that best match your data — the numerical heart of regression. You supply the model shape; SciPy finds the coefficients:

fit a model to data
import numpy as np
def model(x, a, b): # a line: y = a·x + b
return a * x + b
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.1, 4.0, 6.2, 7.9, 10.1])
params, _ = optimize.curve_fit(model, x, y)
a, b = params # best-fit slope & intercept
print(a, b) # ≈ 2.0, 0.0

Root finding

A root is where a function equals zero. root_scalar (or brentq) solves equations that have no neat algebraic answer:

solve f(x) = 0
# Where does x^2 - 2 = 0? (√2)
sol = optimize.root_scalar(lambda x: x**2 - 2, bracket=[0, 2])
print(sol.root) # ≈ 1.4142

Practice

Minimise a simple quadratic with minimize. Then generate noisy points along a line, recover the slope and intercept with curve_fit, and compare to the true values. Finally, find a root of cos(x) - x.

Key takeaways

  1. 01Optimisation finds the input that minimises (or maximises) a function — the basis of ML.
  2. 02optimize.minimize(f, x0) finds a minimum from a starting guess.
  3. 03curve_fit recovers the best-fit parameters of a model — numerical regression.
  4. 04root_scalar / brentq solve f(x) = 0 when there's no algebraic answer.
  5. 05Numerical solvers need a good starting point or bracket, or they miss/diverge.