One way to find the least-squares polynomial fit for a set of data points in Python is to use NumPy's polyfit()
function. This function fits a polynomial of a specified degree to the data using a least-squares approach.
Here is an example code snippet demonstrating how to use polyfit()
to fit a 2nd degree polynomial to a set of data:
main.py416 chars17 lines
Output:
main.py92 chars3 lines
In this example, polyfit()
returns an array of coefficients for the fitted polynomial in descending order of degree. The coefficients can be used with NumPy's polyval()
function to evaluate the polynomial at a set of x-values.
gistlibby LogSnag