Here are a few useful SciPy sample codes showcasing different aspects of the library, including optimization, integration, interpolation, and signal processing.
1. Optimization: Minimizing a Function
This example demonstrates how to minimize a mathematical function using scipy.optimize.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import numpy as np from scipy.optimize import minimize
# Define a function to minimize defobjective_function(x): return x**2 + 10*np.sin(x)
# Initial guess x0 = 2.0
# Perform the minimization result = minimize(objective_function, x0, method='BFGS')
print("Minimum value of the function:", result.fun) print("Value of x that minimizes the function:", result.x)
[Output]
Minimum value of the function: 8.31558557947746
Value of x that minimizes the function: [3.83746713]
2. Integration: Calculating the Area Under a Curve
This example shows how to calculate the definite integral of a function using scipy.integrate.quad.
1 2 3 4 5 6 7 8 9 10
from scipy.integrate import quad
# Define a function to integrate defintegrand(x): return np.exp(-x**2)
# Compute the integral from 0 to infinity result, error = quad(integrand, 0, np.inf)
print("Integral result:", result)
[Output]
Integral result: 0.8862269254527579
3. Interpolation: Interpolating Data Points
This example demonstrates how to interpolate data points using scipy.interpolate.interp1d.
import numpy as np import matplotlib.pyplot as plt from scipy.signal import butter, lfilter
# Generate a noisy signal np.random.seed(0) t = np.linspace(0, 1, 500, endpoint=False) signal = np.sin(2 * np.pi * 7 * t) + 0.5 * np.random.randn(500)
# Design a low-pass filter defbutter_lowpass(cutoff, fs, order=5): nyquist = 0.5 * fs normal_cutoff = cutoff / nyquist b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a
# Apply the filter to the signal deflowpass_filter(data, cutoff, fs, order=5): b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y
# Parameters cutoff = 3.5# Desired cutoff frequency of the filter, Hz fs = 50.0# Sample rate, Hz
# Filter the signal filtered_signal = lowpass_filter(signal, cutoff, fs)
These examples provide a glimpse of the powerful tools available in SciPy for scientific computing, including optimization, integration, interpolation, and signal processing.