0
0
SciPydata~5 mins

Polynomial fitting in SciPy

Choose your learning style9 modes available
Introduction

Polynomial fitting helps us find a smooth curve that best matches a set of points. It is useful to understand trends and make predictions.

You have scattered data points and want to see the overall trend.
You want to predict values between or beyond your data points.
You want to smooth noisy data to see the main pattern.
You want to compare how well different curves fit your data.
Syntax
SciPy
from numpy import polyfit, polyval

coefficients = polyfit(x, y, degree)
fitted_values = polyval(coefficients, x)

polyfit finds the polynomial coefficients that best fit your data.

polyval calculates the y-values using those coefficients.

Examples
Fit a 2nd degree polynomial (a parabola) to points that follow y = x².
SciPy
from numpy import polyfit, polyval

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
coeffs = polyfit(x, y, 2)
fitted = polyval(coeffs, x)
Fit a straight line (1st degree polynomial) to data points.
SciPy
from numpy import polyfit, polyval

x = [0, 1, 2, 3]
y = [1, 3, 7, 13]
coeffs = polyfit(x, y, 1)
fitted = polyval(coeffs, x)
Sample Program

This code fits a 2nd degree polynomial to some sample data points. It prints the polynomial coefficients and the fitted y-values. Then it shows a plot with the original points and the smooth curve.

SciPy
from numpy import polyfit, polyval
import numpy as np
import matplotlib.pyplot as plt

# Sample data points
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 10, 18, 30])

# Fit a 2nd degree polynomial
degree = 2
coeffs = polyfit(x, y, degree)

# Calculate fitted values
fitted_y = polyval(coeffs, x)

# Print coefficients
print('Polynomial coefficients:', coeffs)

# Print fitted values
print('Fitted values:', fitted_y)

# Plot original points and fitted curve
plt.scatter(x, y, color='blue', label='Data points')
plt.plot(x, fitted_y, color='red', label='Fitted polynomial')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Polynomial Fitting Example')
plt.legend()
plt.show()
OutputSuccess
Important Notes

Higher degree polynomials can fit data better but may cause wiggly curves.

Always check if the polynomial degree makes sense for your data.

Plotting helps to see if the fit looks good.

Summary

Polynomial fitting finds a smooth curve to match data points.

Use polyfit to get coefficients and polyval to get fitted values.

Check the fit visually and avoid too high polynomial degrees.