SciPy is a powerful Python library for scientific and technical computing. It is built on top of NumPy and provides advanced tools for integration, optimization, linear algebra, signal processing, and more.
In this topic, you will learn how to:
scipy.integrate for numerical integration.scipy.optimize for optimization tasks.scipy.linalg for linear algebra operations.integrate, optimize, and linalg.You typically install SciPy using pip, then import the specific submodules you need in your script.
scipy.integrate → Numerical integration, ODE solvers.scipy.optimize → Minimization, curve fitting, root finding.scipy.linalg → Advanced linear algebra routines.
# Install SciPy
pip install scipy
scipy.integrateUse integrate.quad to compute the definite integral of a function over an interval.
from scipy import integrate
# Define a function
def f(x):
return x**2
# Compute definite integral from 0 to 1
result, error = integrate.quad(f, 0, 1)
print(result) # Expected output: 0.33333333333333337
scipy.optimizeUse minimize to find the minimum value of a function.
from scipy.optimize import minimize
# Define the function to minimize
def f(x):
return (x - 3)**2
# Call minimize starting from initial guess 0
result = minimize(f, 0)
print(result.x) # Expected output: [3.]
scipy.linalgUse linalg.solve to solve systems of linear equations.
from scipy import linalg
import numpy as np
# Create coefficient matrix A and right-hand side vector b
A = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
# Solve the linear system Ax = b
x = linalg.solve(A, b)
print(x) # Expected output: [-4. 4.5]
f(x) = x² from 0 to 1. The analytical result is 1/3, and SciPy returns a value close to 0.33333333333333337 plus an estimate of the numerical error.(x - 3)², which has its minimum at x = 3. The minimize function starts from an initial guess (0) and iteratively finds the minimum, returning [3.] as the solution.Ax = b where A = [[1, 2], [3, 4]] and b = [5, 6]. The result [-4. 4.5] is the vector x that satisfies the equations defined by A and b.from scipy import integrate or from scipy import linalg, to keep your code clear.integrate, optimize, and linalg.scipy.integrate.quad to compute the integral of sin(x) between 0 and π.scipy.optimize.minimize to find the minimum of a different function, for example (x + 2)² + 1.3×3 matrix and a vector b, then solve the system Ax = b using scipy.linalg.solve.scipy.stats or scipy.signal and try a basic function from each.