Numerical optimization
Quick answer
Numerical optimization searches for parameter values that minimize an objective, often without an algebraic solution. A bounded scalar problem restricts a single parameter to an interval. scipy.optimize.minimize_scalar with method="bounded" uses objective evaluations to seek a local minimum within specified bounds. It returns an OptimizeResult with candidate x, objective fun and success status. Examples use local Python 3.13.5, SciPy 1.17.0, NumPy 2.3.5 and Matplotlib 3.10.8 as applicable. All fixtures are synthetic; ByteMind library execution is unverified.
Find a feasible calibration offset
The desired offset is 3 units and the permitted range is 0 to 5 units. The objective is squared deviation.
from scipy.optimize import minimize_scalarresult = minimize_scalar(lambda x: (x - 3)**2, bounds=(0, 5), method='bounded')print(result.success)print(round(float(result.x), 4))print(round(float(result.fun), 4))Expected output:
True3.00.0The quadratic has a unique minimum at 3, inside the bounds. The numerical result agrees with the analytic solution.
Check endpoints explicitly
The unconstrained optimum is outside the interval. Compare the numerical candidate and both boundaries because an endpoint may be best.
from scipy.optimize import minimize_scalardef loss(x): return (x - 8)**2r = minimize_scalar(loss, bounds=(0, 5), method='bounded')assert r.successx = min([0., float(r.x), 5.], key=loss)print(x, loss(x))Expected output:
5.0 9.0The best feasible offset is 5 and the objective is 9. The interior search alone may return a point just short of the boundary.
Common mistakes
Success is a solver termination status, not a proof of global optimality. Nonconvex objectives can have several minima; compare candidates and use domain knowledge. Bounds constrain parameters, not loss values. Check finite objectives, termination and units; use training data only for fitting.
Practice and next steps
Move the desired offset to -2 and predict the constrained optimum. Explain why exact clipping works for a quadratic but not for arbitrary objectives. The separate pure-Python exercise assesses the underlying calculation, not library execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numerical optimization — knowledge check
Apply scientific computing and visualization reasoning to synthetic examples.
What does bounds=(0,5) constrain?
Minimize (x-8)^2 for 0<=x<=5. Where is the optimum?
What does result.success establish?
For a nonconvex objective, what is a useful follow-up?
Why check both endpoints in a bounded problem?