least squares polynomial in python

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.py
import numpy as np

# Create some example data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.3, 3.5, 4.2, 5.0, 6.1])

# Fit a 2nd degree polynomial to the data
coeffs = np.polyfit(x, y, 2)

# Use the fitted polynomial to make predictions
x_pred = np.array([6, 7, 8])
y_pred = np.polyval(coeffs, x_pred)

# Print the coefficients and predicted values
print("Coefficients:", coeffs)
print("Predicted values:", y_pred)
416 chars
17 lines

Output:

main.py
Coefficients: [ 0.24285714 -0.72857143  3.15714286]
Predicted values: [ 7.7   11.2   14.85]
92 chars
3 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