Saturday, October 28, 2023

Numworks: Polynomial Fit with Numpy (Software version 21 or later)

Numworks:  Polynomial Fit with Numpy  (Software version 21 or later)



The scripts polyfit.py and polyfitg.py perfectly fit 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.  


Numworks:  polyfit


polyfit.py:    Fit a number of points to a curve using the numpy module

403 bytes


from math 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(p)




Numworks:  polyfitg


polyfitg.py:   Same as polyfit except a graph of the polynomial is drawn.   The coefficients are shown for 3 before the graph is drawn.  

743 bytes 


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





Eddie


All original content copyright, © 2011-2023.  Edward Shore.   Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited.  This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author. 


Fun with the HP 30b

Fun with the HP 30 b Introduction The following programs are for the HP 30b Business Professional. Did you know that the 30b...