0
0
SciPydata~5 mins

Linear vs cubic interpolation in SciPy

Choose your learning style9 modes available
Introduction

Interpolation helps us estimate values between known data points. Linear interpolation connects points with straight lines, while cubic interpolation uses smooth curves for better accuracy.

Estimating missing temperature data between recorded days.
Predicting sales figures between monthly reports.
Smoothing sensor readings in a device for better analysis.
Creating smooth animations by estimating positions between frames.
Syntax
SciPy
from scipy.interpolate import interp1d

# Create interpolation function
f = interp1d(x, y, kind='linear')  # or kind='cubic'

# Use function to find new y values
new_y = f(new_x)

kind can be 'linear' for straight lines or 'cubic' for smooth curves.

The input arrays x and y must be sorted and of the same length.

Examples
Linear interpolation estimates the value at 1.5 by connecting points with straight lines.
SciPy
from scipy.interpolate import interp1d

x = [0, 1, 2, 3]
y = [0, 1, 4, 9]

f_linear = interp1d(x, y, kind='linear')
print(f_linear(1.5))
Cubic interpolation estimates the value at 1.5 using a smooth curve fitting the points.
SciPy
from scipy.interpolate import interp1d

x = [0, 1, 2, 3]
y = [0, 1, 4, 9]

f_cubic = interp1d(x, y, kind='cubic')
print(f_cubic(1.5))
Sample Program

This program shows how linear and cubic interpolation estimate values between known points. It prints the interpolated values at 2.5 and plots both methods for comparison.

SciPy
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

# Known data points
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 4, 9, 16])

# Points to estimate
x_new = np.linspace(0, 4, 50)

# Create interpolation functions
f_linear = interp1d(x, y, kind='linear')
f_cubic = interp1d(x, y, kind='cubic')

# Calculate interpolated values
y_linear = f_linear(x_new)
y_cubic = f_cubic(x_new)

# Print some example values
print(f"Linear interpolation at 2.5: {f_linear(2.5)}")
print(f"Cubic interpolation at 2.5: {f_cubic(2.5)}")

# Plot results
plt.plot(x, y, 'o', label='Data points')
plt.plot(x_new, y_linear, '-', label='Linear')
plt.plot(x_new, y_cubic, '--', label='Cubic')
plt.legend()
plt.title('Linear vs Cubic Interpolation')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
OutputSuccess
Important Notes

Linear interpolation is faster but less smooth.

Cubic interpolation is smoother but needs at least 4 points.

Use cubic interpolation when you want a smooth curve that fits the data well.

Summary

Linear interpolation connects points with straight lines for quick estimates.

Cubic interpolation fits smooth curves for more accurate estimates.

Choose the method based on your need for speed or smoothness.