Optimization with scipy.optimize
The scipy.optimize
module is designed for finding optimal values of functions and solving equations.
It's commonly used in scientific computing, engineering, and data analysis to:
- Minimize or maximize a function
- Fit curves to data
- Solve equations and systems of equations
Setting Up
Import the required modules:
Import NumPy and SciPy Optimize
import numpy as np
from scipy import optimize
Example 1: Minimizing a Function
Use the minimize()
function to find the minimum of a 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)
is the objective function.x0
is the starting guess.- The result object contains the optimal
x
and the minimum value of the function.
Example 2: Solving an Equation
Use the root()
function to find where an equation 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:
- We're solving the equation
cos(x) = x
. - The
root()
function finds the value ofx
where the equation equals zero.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.