fitdata.py

Created by vnap0v

Created on June 06, 2025

844 Bytes

The Numworks calculator has the Regression app to find polynomials which best fit given data. The calculator’s Python app has a numpy library which contains the function polyfit() for the same purpose. Another function called polyval() evaluates a polynomial for a set of x values. This script demonstrates numpy.polyfit() and numpy.polyval(). Tested on the calculator using software version 23.2.6. Also works in CPython on a PC


import numpy as np
import matplotlib.pyplot as plt

# data points
data_x=(2,4,8,12,15,18,21,23,27,29)
data_y=(-16.1,-3.8,8.9,1.8,-3.5,-6.2,2.4,12.2,26.3,42.2)

# string repr. of polynomial
def pol2str(pol):
  s=""
  for k,coeff in enumerate(pol):
    p=(len(pol)-1)-k
    if p==0:
      s+="{0:+f}".format(coeff)
    elif p==1:
      s+="{0:+f}*X".format(coeff)
    else:
      s+="{0:+f}*X**{1}\n".format(coeff,p)
  return s
# plot data
plt.scatter(data_x,data_y,color="blue")
# calc and plot polynomials
colors=("red","green","orange","purple")
x=np.linspace(data_x[0],data_x[-1],20)
for d in range(1,4):
  pol=np.polyfit(data_x,data_y,d)
  print("Fit polynomial of degree {0}".format(d))
  print(pol2str(pol)) 
  fit_y=np.polyval(pol,x)
  plt.plot(x,fit_y,color=colors[d-1])
plt.grid()
input("Hit <Exe> for graph")
plt.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 cookies policy.