To perform optimization in Python, define an objective function and pass it to scipy.optimize.minimize with a starting guess, choosing a method that matches your problem: unconstrained, bounded, constrained or linear. For linear programs use scipy.optimize.linprog, and for fitting a model to data use curve_fit or least_squares.
SciPy covers most small and medium problems. This guide walks through each case with runnable code, explains how to read the result object and lists what to use when SciPy is not enough.
minimize takes the objective, an initial guess x0 and an optional method. It returns an OptimizeResult with the solution in x, the value in fun and a success flag.
If you do not give method, SciPy picks BFGS, L-BFGS-B or SLSQP depending on whether you pass bounds or constraints. Always check result.success and result.message before trusting result.x.
| Method | Use it when |
|---|---|
BFGS, L-BFGS-B | Smooth function, many variables (L-BFGS-B also supports bounds) |
Nelder-Mead, Powell | No gradient available or the function is noisy |
SLSQP, trust-constr | You have constraints |
Bounds restrict each variable to a range. Constraints are dictionaries or LinearConstraint and NonlinearConstraint objects.
In SciPy, "ineq" means the function must be greater than or equal to zero, and "eq" means it must equal zero. Getting this sign wrong is a common source of wrong answers.
linprog always minimises, so negate the objective to maximise. The constraints are written as A_ub @ x <= b_ub.
The default highs solver is fast and reliable. Variables are non-negative by default, but stating the bounds explicitly makes the model easier to read. For integer variables use scipy.optimize.milp.
Least-squares fitting is an optimisation problem too, and curve_fit wraps it.
minimize finds a local minimum, which depends on the starting point. For functions with many local minima, use global methods from SciPy: differential_evolution, dual_annealing, shgo or basinhopping.
When SciPy is not enough, consider CVXPY for convex problems, OR-Tools for scheduling and routing, Pyomo for large models, and Optuna for hyperparameter search.
Use L-BFGS-B or BFGS for smooth unconstrained problems, SLSQP or trust-constr with constraints, and Nelder-Mead when you have no gradient. For linear problems use linprog.
SciPy only minimises, so minimise the negative of your function and negate the result.
The function has multiple local minima and the solver stops in the nearest one. Try several starts or a global method such as differential_evolution.
No, SciPy approximates them numerically, but supplying jac (or using automatic differentiation libraries such as JAX) makes the solver faster and more accurate.
Use scipy.optimize.minimize for general problems, pick the method by whether you have constraints or gradients, and check the result's success flag. Use linprog for linear programs, curve_fit for fitting models, and global optimisers when the landscape has many local minima.