What it is
SciPy is an open-source Python library used for scientific and technical computing. It builds on NumPy arrays and provides a wide range of algorithms for optimization, integration, interpolation, eigenvalue problems, algebraic equations, differential equations, and signal processing.
SciPy provides modules for optimization, linear algebra, signal and image processing, statistics, integration, and more. It integrates seamlessly with NumPy arrays and allows advanced scientific computations with minimal code.
Installation
pip install scipyGetting started
The smallest useful thing you can do with it, and what each part means.
from scipy import optimize
f = lambda x: (x - 3)**2
result = optimize.minimize(lambda v: f(v[0]), x0=[0])
print(result)from scipy import integrate
result, error = integrate.quad(lambda x: x**2, 0, 1)
print(result)Advanced usage
Where the library earns its place over a simpler alternative.
from scipy import linalg
import numpy as np
A = np.array([[3,2],[1,2]])
b = np.array([5,5])
x = linalg.solve(A, b)
print(x)from scipy import signal
import numpy as np
b, a = signal.butter(3, 0.05)
z = signal.lfilter(b, a, np.random.randn(1000))
print(z[:10])from scipy import interpolate
import numpy as np
x = np.arange(5)
y = np.sin(x)
f = interpolate.interp1d(x, y)
print(f(2.5))Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- ValueError
- Ensure inputs have correct shapes and types expected by the function.
- LinAlgError
- Check that matrices are square and non-singular when performing linear algebra operations.
Best practices
- Use NumPy arrays for input data to ensure compatibility with SciPy functions.
- Check function domains and constraints when using optimization routines.
- Leverage built-in documentation for each submodule to understand parameter options.
- Use `scipy.constants` for physical constants to improve code readability and accuracy.
- Profile computations for large datasets using vectorized operations rather than loops.
Background
Why it exists, and what it was reacting to.
SciPy was initially created in 2001 by Travis Oliphant, Eric Jones, and Pearu Peterson. It was designed to extend NumPy’s capabilities by providing high-level functions for scientific computations. SciPy has since become a core library in the Python scientific ecosystem and is widely used in engineering, physics, machine learning, and data analysis.
