Math and Science with Python

Find the Minimum of a Function with scipy.optimize.minimize

Search for the input that makes a function smallest, choose a method, and keep the answer inside bounds.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • minimize with a starting point x0
  • Reading .x, .fun and .success
  • Methods and bounds
Results from the example
Bowl
  • (3, -1)
  • value 2
Rosenbrock
  • (1, 1)
  • BFGS
With bounds
  • (2, -0.5)
  • value 3.25

Search for the lowest point

The problem

Optimisation problems are everywhere: the cheapest design, the shortest time, the best parameters for a model. When the function is too complicated to differentiate and solve by hand, a numerical optimiser searches for the minimum.

Think of it like this

minimize is like a hiker in fog looking for the bottom of a valley. The hiker feels which way the ground slopes and keeps walking downhill until every direction goes up. Bounds are fences the hiker may not cross.

From a hiker in fog to code
f(p)⛰️ The height of the ground
x0=[0, 0]🚩 Where the hiker starts
minimize(f, x0)🥾 Walk downhill until it stops going down
bounds=[(0, 2), (-0.5, 0.5)]🚧 Fences the hiker cannot cross
Walk downhill until there is nowhere lower to go.
In one sentence

scipy.optimize.minimize(fun, x0) searches for the point where fun is smallest, starting from x0. It returns a result object with the point .x, the value .fun and whether it succeeded.

Key points

  1. The function takes one array of parameters and returns one number.
  2. result.x is the best point and result.fun the value there.
  3. method="BFGS" picks the algorithm; the default depends on bounds and constraints.
  4. With bounds, the minimum of f moves to the edge, (2, -0.5), with value 3.25.

When should you use it?

  • Fitting model parameters by minimising an error.
  • Engineering design: least material, lowest cost.
  • Maximising profit or area by minimising its negative.

When not to use it

  • Fitting a model to data points: curve_fit wraps this for you.
  • Functions with many separate valleys: a local method may stop in the wrong one; try scipy.optimize.differential_evolution.

Example code

Open in editor →
main.py
import numpy as np
from scipy.optimize import minimize

# A bowl-shaped function with its minimum at (3, -1)
def f(p):
    x, y = p
    return (x - 3)**2 + (y + 1)**2 + 2

result = minimize(f, x0=[0, 0])
print("Minimum at:", result.x.round(4).tolist())
print(f"Minimum value: {result.fun:.4f}")
print("Success:", result.success)

# The Rosenbrock function: a curved valley, minimum at (1, 1)
def rosen(p):
    x, y = p
    return (1 - x)**2 + 100 * (y - x**2)**2

result = minimize(rosen, x0=[-1.2, 1], method="BFGS")
print("Rosenbrock minimum:", result.x.round(4).tolist())

# Bounds: keep x between 0 and 2, y between -0.5 and 0.5
result = minimize(f, x0=[1, 0], bounds=[(0, 2), (-0.5, 0.5)])
print("With bounds:", result.x.round(4).tolist(), f"value {result.fun:.4f}")
Get a Run button for this example

Result of running the code

Minimum at: [3.0, -1.0]
Minimum value: 2.0000
Success: True
Rosenbrock minimum: [1.0, 1.0]
With bounds: [2.0, -0.5] value 3.2500

Code explanation

f has its lowest point at (3, -1) with the value 2, and minimize finds it from the start x0=[0, 0]. The result has .x for the point, .fun for the function value and .success. The Rosenbrock function has a narrow curved valley that is hard for simple methods; BFGS still reaches its minimum at (1, 1). With bounds, x may only go up to 2 and y down to -0.5, so the best allowed point is (2, -0.5) with the value 3.25.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Writing the function with separate arguments

minimize passes one array, not several numbers.

Problem
def f(x, y):
Fix
def f(p):
    x, y = p

Using minimize to find a maximum

To maximise, minimise the negative of the function.

Problem
minimize(profit, x0)
Fix
minimize(lambda p: -profit(p), x0)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson