Saturday, 7 December 2024

Curve Fitting with Polynomials using Python

Topic: Method of Curve Fitting with Polynomial Functions;

Subject: Numerical Methods;

Tool: Python;

By: Gani Comia, Dec. 2024;

Curve fitting with polynomials finds a polynomial equation of a given degree that approximates the set of data points. Curve fitting is used in the following applications:

  • Data Smoothing
  • Predictive Modelling
  • Scientific Analysis

The general form of a polynomial function of degree n is:

$$P(x)\;=\;{a_n\,x^n}+{a_{n-1}\,x^{n-1}}+\ldots+{a_1\,x}+{a_0}$$

This article shows a Python script as toolbox to implement the method of curve fitting with polynomials. The script requires numerical data for both dependent and independent variables. For a given sample of data points in Fig.1., an approximate polynomial curve of 3rd degree shown in Fig.2. can be calculated and plotted using Python script.

$$xdata = [ 0 \quad 1 \quad 2 \quad 3 \quad 4 \quad 5 \quad 6 \quad 7 ]$$

$$ydata = [ 5 \quad 10 \quad 60 \quad 50 \quad 130 \quad 220 \quad 300 \quad 280 ]$$

Fig.1. Sample Data Points for Approximating Polynomial Curve.

Below is the approximate polynomial curve that closely fit the given data points.

Fig.2. Polynomial Curve of 3rd Degree from Data Points.

Python Script

# -*- coding: utf-8 -*-
"""
Created on Mon Nov  7 21:08:48 2024
@author: Gani Comia
"""
'''
Curve Fitting with Polynomials for a given xdata and ydata
'''
import numpy as np
import matplotlib.pyplot as plt

# given: xdata and ydata
xdata = np.array([0. , 1. , 2. , 3. , 4. , 5. , 6. , 7.])
ydata = np.array([5. , 10. , 60. , 50. , 130. , 220. , 300. , 280.])

# solution:
# solving for coefficients of polynomial fit for cubic (degree=3)
# z is an array of coefficients , highest first , i.e.
# z = np.array ([c_3, c_2 , c_1 , c_0])
z = np.polyfit(xdata, ydata, 3)
print("\n",z,"\n") 

# ‘poly1d‘ returns the polynomial function from coefficients    
p = np.poly1d(z)
print(p)

# polynomial's curve data points
xs = [0.1 * i for i in range (70)]  # from 0 to 7, step=0.1
ys = [p(x) for x in xs]   # evaluate p(x) for all x in list xs

# creating plot of data points and polynomial curve for visualization
plt.plot(xdata, ydata, 'o', label='data points') # data points
plt.plot(xs, ys, label='fitted curve')    # polynomial fit
plt.title('Curve Fitting with Polynomials')
plt.ylabel('y-value')
plt.xlabel('x-value')
plt.legend()
plt.grid()
plt.show()

On the above script, Python Numpy’s utilities, np.polyfit(), returns the polynomial coefficients of the given degree that approximately fits on the given data points.  Numpy’s np.poly1d() creates a polynomial functions for plotting and calculation.

Feel free to comment for inquiry, clarification, or suggestion for improvement. Drop your email to request the softcopy of the file.


No comments:

Post a Comment

C++ and Python for Numerical Solution to Spring-Mass-Damper Model

Topic: SDOF Spring-Mass-Damper System Subject: Numerical Methods & Mechanical Vibration Tools: C++, CodeBlocks, GitHub Copilot, LabP...