0% found this document useful (0 votes)
9 views1 page

Polynomial Py

The document contains a Python script for polynomial curve fitting, authored by Bikalpa Bhattarai. It defines a function to perform polynomial regression and plots the fitted curve against the provided data points. The script uses NumPy and Matplotlib libraries to compute coefficients and visualize the results.

Uploaded by

bikalpab30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Polynomial Py

The document contains a Python script for polynomial curve fitting, authored by Bikalpa Bhattarai. It defines a function to perform polynomial regression and plots the fitted curve against the provided data points. The script uses NumPy and Matplotlib libraries to compute coefficients and visualize the results.

Uploaded by

bikalpab30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

7/7/25, 7:47 PM polynomial.

py

~\Desktop\lab\Curve Fitting\polynomial.py

1 #Polynomial Curve Fitting


2 #Bikalpa Bhattarai 080BEL023
3 import numpy as np
4 import matplotlib.pyplot as plt
5
6 def polynomial_regressio­
n(x, y, degree=3):
7 n = len(x)
8 A = np.zeros((degree + 1, degree + 1))
9 B = np.zeros(degree + 1)
10
11 for i in range(degree + 1):
12 for j in range(degree + 1):
13 A[i, j] = np.sum(x**(i + j))
14
15 for i in range(degree + 1):
16 B[i] = np.sum(y * x**i)
17
18 coeffs = np.linalg.solve(A, B)
19 return coeffs
20
21 # Input data
22 x = np.array([1, 1.5, 2, 2.5, 3, 3.5, 4])
23 y = np.array([1.1, 1.3, 1.6, 2.0, 2.7, 3.4, 4.1])
24
25 coeffs = polynomial_regressio­
n(x, y, degree=3)
26 a0, a1, a2, a3 = coeffs
27
28 print(f"Coefficients:\na0 = {a0:.5f}\na1 = {a1:.5f}\na2 = {a2:.5f}\na3 =
{a3:.5f}")
29
30 x_fit = np.linspace(min(x), max(x), 200)
31 y_fit = a0 + a1*x_fit + a2*x_fit**2 + a3*x_fit**3
32
33 # Plotting
34 plt.figure(figsize=(9,6))
35 plt.scatter(x, y, color='red', label='Data Points')
36 plt.plot(x_fit, y_fit, color='blue', label='Cubic Polynomial Fit')
37
38 plt.xlabel('x')
39 plt.ylabel('y')
40 plt.title('Polynomial Least Squares Fit\nBikalpa Bhattarai | 080BEL023')
41 plt.legend()
42 plt.grid(True)
43 plt.tight_layout()
44 plt.show()

localhost:51524/1d10120d-7f12-4c2f-aca6-43a1420bdbc4/ 1/1

You might also like