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()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.