Module 3 · Section 8 of 11
Lesson 3.7 - Optimization
Target: ~10 min read - 20 min hands-on
Overview
scipy.optimize.minimize finds the input value(s) that minimize a function you define -
perfect for "least material," "lowest cost," or "minimum loss" problems. We'll minimize
the sheet-metal area of an open-top cylindrical tank for a required volume.
Why This Matters (Engineering Context)
"Smallest / cheapest design that still meets the requirement" is a constrained
minimization whatever the field - a tank, a heat sink, a conductor size, an order
quantity. Knowing minimize turns it into a few lines.
Code-Along
from scipy.optimize import minimize
import numpy as np
# [Chemical/Mechanical] minimize the sheet area of an OPEN-TOP cylindrical tank
# for a fixed volume V = pi r^2 h, choosing the radius r (h then follows from V).
V_req = 2.0 # m^3
# The objective: minimize() always passes the variables as an ARRAY, so the
# single radius arrives as r[0]. Return the quantity we want to make smallest.
def surface_area(r):
r = r[0]
h = V_req / (np.pi * r ** 2) # height implied by the fixed volume
return np.pi * r ** 2 + 2 * np.pi * r * h # base area + wall area (no lid)
# x0 = starting guess; bounds keep the search in physically sensible radii
result = minimize(surface_area, x0=[0.5], bounds=[(0.1, 3.0)])
r_opt = result.x[0] # result.x holds the optimal variables
h_opt = V_req / (np.pi * r_opt ** 2)
print(f"Optimal radius: {r_opt:.4f} m")
print(f"Height at optimum: {h_opt:.4f} m (h / r = {h_opt / r_opt:.2f})")
print(f"Minimum sheet area: {result.fun:.4f} m^2") # result.fun = objective at the optimum
print(f"Converged: {result.success}")
Run it: for an open-top cylinder the optimal proportion is h / r = 1 (height
equals radius) - a classic analytic result the optimizer should reproduce to a couple
of decimals.
Practice Exercises
- Change
V_reqto5.0m^3 and re-optimize - do the optimalrandhstill satisfyh / r = 1? - Add a constraint that the height must not exceed
1.5m (a headroom limit) and re-solve. - Minimize the area for a closed tank instead (add a top:
2 * pi * r**2). What is the optimalh / rnow?
# Try the practice exercises here
Knowledge Check
- What does
scipy.optimize.minimizerequire you to define besides the objective function? - What does it mean for a constraint to be "active" or "binding" at the optimum?
- Why are
boundsuseful in addition toconstraints?
Answer key
- An objective function, and optionally constraints and/or bounds on the variables
- The optimal solution sits exactly at the edge of what the constraint allows
- Bounds keep the optimizer out of physically meaningless values during the search
30 / 63 sections · Course home · Join the coaching cohort