SciPy is a Python library used for scientific and technical computing. It builds on NumPy and provides advanced tools to solve mathematical problems like integration, optimization, solving equations, statistics and signal processing. SciPy is widely used in science, engineering and data analysis because it makes complex calculations simple and fast.
SciPy packages
Package | Usage |
|---|---|
scipy.constants | Physical and mathematical constants |
scipy.integrate | Integration and ordinary differential equation solvers |
scipy.interpolate | Interpolation |
scipy.io | Input/output (including MATLAB files) |
scipy.linalg | Linear algebra |
scipy.optimize | Optimization |
scipy.signal | Signal processing |
scipy.spatial | Spatial data structures and algorithms |
scipy.special | Special mathematical functions |
Basic Functions in SciPy
1. Integration
- Integration is a technique used for calculating the integral of a function when an analytical solution is difficult or impossible to obtain.
- This code calculates the definite integral of the function from 0 to 1 using SciPy’s integrate.quad method.
from scipy import integrate
import numpy as np
f = lambda x: x**2
result, error = integrate.quad(f, 0, 1)
print(result)
Output:
0.33333333333333337
2. Optimization
- Optimization involves finding the best possible solution.
- This code finds the value of x that makes the function as small as possible. Using optimize.minimize, SciPy starts searching from x = 0 and iteratively moves towards the minimum point.
from scipy import optimize
f = lambda x: (x - 3)**2
result = optimize.minimize(f, x0=0)
print(result.x)
Output:
[2.99999998]
3. Linear algebra
- This code imports NumPy and det from scipy.linalg to calculate the Determinant of a 2×2 matrix A. The det(A) function computes the value using the formula ad - bc and the result is printed.
import numpy as np
from scipy.linalg import det
A = np.array([[2, 2],
[3, 4]])
# Calculate determinant
d = det(A)
print("Determinant:", d)
Output:
Determinant: 2.0
4. Interpolation
- Interpolation is a technique to estimate unknown value points that fall between known data points.
- This code creates an interpolation function based on given data points x and y where y represents values of x squared. Using interp1d it builds a function f that estimates values between the known points.
from scipy.interpolate import interp1d
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([0, 1, 4, 9])
f = interp1d(x, y)
print(f(1.5))
Output:
2.5