This project implements a natural cubic spline interpolation function in Python, including smoothness analysis.
The natural_cubic_spline function takes a list of 2D points (x, y) and constructs a natural cubic spline that passes through all points exactly. This method is chosen over high-degree polynomial interpolation to avoid oscillations and ensure smoothness.
The program also computes the integral of the squared second derivative as a quantitative measure of smoothness and compares it with high-degree polynomial interpolation, demonstrating the superiority of splines in avoiding the Runge phenomenon.
- Avoids Runge Phenomenon: High-degree polynomials can oscillate wildly near endpoints, even with smooth data.
- Piecewise Smoothness: Cubic splines use piecewise cubic polynomials, providing C2 continuity (continuous value, first, and second derivatives).
- Natural Boundaries: Second derivatives are set to zero at endpoints, preventing unnatural curvature outside the data range.
- Stability: More numerically stable and efficient for large datasets.
The Runge phenomenon illustrates the instability of high-degree polynomial interpolation. Even for smooth functions, interpolating polynomials of high degree can exhibit large oscillations near the interval boundaries, especially with equispaced points. This makes them unreliable for approximation, whereas splines provide stable, smooth interpolations.
The integral of the squared second derivative over the interpolation interval quantifies smoothness:
- The second derivative measures local curvature.
- Integrating its square gives the total "energy" or variation in curvature.
- Minimizing this integral leads to smoother curves, as it penalizes rapid changes in curvature.
- Natural cubic splines are optimal in this sense among interpolating functions.
from spline_interpolation import NaturalInterpolator
# Load from CSV (expects two columns: x, y)
points = NaturalInterpolator.load_points_from_csv('data.csv')
interpolator = NaturalInterpolator()
interpolator.fit(points) # Validates at least 10 distinct x-values
# Evaluate at a point
value = interpolator.evaluate(2.5)
# Compute smoothness measure
smoothness = interpolator.smoothness_measure()
# Plot
interpolator.plot()The CSV file should have at least two columns: x and y values. Headers are optional; the first two columns are used. Non-numeric rows are skipped. At least 10 distinct x-values are required.
- numpy
- scipy
- matplotlib
python spline_interpolation.pyThis will create a spline from sample quadratic points, evaluate it, compute smoothness measures for both spline and high-degree polynomial, compare them, and display a plot showing both interpolation methods.