Search code examples
numpypolynomialscoefficients

polynomial fitting of a signal and plotting the fitted signal


I am trying to use a polynomial expression that would fit my function (signal). I am using numpy.polynomial.polynomial.Polynomial.fit function to fit my function(signal) using the coefficients. Now, after generating the coefficients, I want to put those coefficients back into the polynomial equation - get the corresponding y-values - and plot them on the graph. But I am not getting what I want (orange line) . What am I doing wrong here? enter image description here

Thanks.

import math
def getYValueFromCoeff(f,coeff_list): # low to high order
    y_plot_values=[]

    for j in range(len(f)):
        item_list= []
        for i in range(len(coeff_list)):
            item= (coeff_list[i])*((f[j])**i)
            item_list.append(item)
        y_plot_values.append(sum(item_list))
    print(len(y_plot_values))
    return y_plot_values

from numpy.polynomial import Polynomial as poly 
import numpy as np
import matplotlib.pyplot as plt     

no_of_coef= 10

#original signal
x = np.linspace(0, 0.01, 10)
period = 0.01
y = np.sin(np.pi * x / period)

#poly fit
test1= poly.fit(x,y,no_of_coef)
coeffs= test1.coef
#print(test1.coef)
coef_y= getYValueFromCoeff(x, test1.coef)
#print(coef_y)

plt.plot(x,y)
plt.plot(x, coef_y)

Solution

  • If you check out the documentation, consider the two properties: poly.domain and poly.window. To avoid numerical issues, the range poly.domain = [x.min(), x.max()] of independent variable (x) that we pass to the fit() is being normalized to poly.window = [-1, 1]. This means the coefficients you get from poly.coef apply to this normalized range. But you can adjust this behaviour (sacrificing numerical stability) accordingly, that is, adjustig the poly.window will make your curves match:

    ...
    test1 = poly.fit(x, y, deg=no_of_coef, window=[x.min(), x.max()])
    ...
    

    But unless you have a good reason to do that, I'd stick to the default behaviour of fit().

    As a side note: Evaluating polynomials or lists of coefficients is already implemented in numpy, e.g. using directly

    coef_y = test1(x)
    

    or alternatively using np.polyval.