Skip to main content
Practice

Optimization with scipy.optimize

The scipy.optimize module provides tools for finding optimal values of functions and solving equations.

It’s widely used in scientific computing, engineering, and data analysis to:

  • Minimize or maximize mathematical functions
  • Fit models or curves to data
  • Solve equations or systems of equations numerically

Setting Up

First, import the necessary libraries:

Import NumPy and SciPy Optimize
import numpy as np
from scipy import optimize

Example 1: Minimizing a Function

Use optimize.minimize() to find the minimum value of a mathematical function.

Minimize a Function
# Define a function: f(x) = x^2 + 5*sin(x)
def func(x):
return x**2 + 5*np.sin(x)

# Find the minimum starting from an initial guess
result = optimize.minimize(func, x0=2)

print("Optimal x value:", result.x[0])
print("Function value at optimum:", result.fun)

Explanation:

  • func(x) — the objective function to minimize
  • x0 — the initial guess for x
  • The result object (result) contains both the optimal value of x and the minimum function value

Example 2: Solving an Equation

Use optimize.root() to find the roots of equations, i.e., the points where a function equals zero.

Find the Root of an Equation
# Equation: cos(x) - x = 0
def equation(x):
return np.cos(x) - x

root_result = optimize.root(equation, x0=0.5)

print("Root found at:", root_result.x[0])

Explanation:

  • Here, we’re solving the equation cos(x) = x.
  • The root() function searches for the value of x where the function output equals zero — the mathematical root.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.