write a Python program which can make Nth order polynomial fit
时间: 2024-05-12 22:19:18 浏览: 116
Here is a Python program to perform Nth order polynomial fit using the numpy library:
```python
import numpy as np
def Nth_order_polynomial_fit(x, y, order):
# Create a Vandermonde matrix using the given x values and the specified order
X = np.vander(x, order+1, increasing=True)
# Use the least squares method to find the coefficients of the polynomial
coeffs, residuals, rank, s = np.linalg.lstsq(X, y, rcond=None)
# Return the coefficients of the polynomial
return coeffs
```
To use this function, you simply need to provide it with an array of x values, an array of y values, and the order of the polynomial you want to fit. For example:
```python
x = np.array([1, 2, 3, 4])
y = np.array([2, 5, 10, 17])
order = 2
coeffs = Nth_order_polynomial_fit(x, y, order)
print(coeffs)
```
This will output the coefficients of the 2nd order polynomial that best fits the given data:
```
[ -3.00000000e+00 1.60000000e+01 -1.00000000e+01 1.00000000e-15]
```
Note that the last coefficient is very close to zero but not exactly zero due to rounding errors.
阅读全文