polyfitg.py

Created by ews31415

Created on September 26, 2023

743 Bytes

Perfectly fits a polynomial to a set of points. For a set of n points, a polynomial of degree n-1 can be perfect fit to the set of points. For instance, 2 points fit a perfect line, 3 points fit a quadratic polynomial, and 4 points fit a cubic polynomial. Software version 21 or later is required as the numpy module is used.


from math import *
from time import *
from matplotlib.pyplot import *
import numpy as np

# 2023-09-25 EWS
n=input("number of points? ")
n=int(n)
d=n-1
x=np.ones(n)
y=np.ones(n)
k=0

while k<n:
  print("point "+str(k+1))
  x[k]=float(input("x? "))
  y[k]=float(input("y? "))
  k+=1

p=np.polyfit(x,y,d)

# list coefficients
print("polynomial vector:")
print("x**n:  coef")

for k in range(n):
  print(str(n-k-1),":  ",str(p[k]))

print("\nplotting...")
sleep(3)

# graphing portion
c=(np.max(x)-np.min(x))/100
xc=[]
yc=[]

for i in range(101):
  xp=np.min(x)+i*c
  yp=np.polyval(p,xp)
  xc.append(xp)
  yc.append(yp)

axis((min(xc)-.5,max(xc)+.5,min(yc)-.5,max(yc)+.5)) 
axis(True)
grid(True)
plot(xc,yc,color="purple")
show()