### Polynomial fit¶

In this short python example we will fit discrete data with polynomial function. Polynomials of higher degrees have tendency to oscillate substantially.

We will use numpy polyfit built-in function.

In [3]:
import matplotlib.pyplot as plt
import numpy as np

# nicer jupyter environment
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
%config InlineBackend.figure_format = 'retina'

%matplotlib inline

In [4]:
# discrete dataset
x_data = np.array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
y_data = np.array([0.5, 1., 0.8, -1., -1.5, -0.7, 0., 0.6, 1.2, 1.5, 1.7])

# x values for the polynomial fit, 200 points
x = np.linspace(-3.0, 12.0, 200)

# polynomial fit of degree 3
p3 = np.polyfit(x_data, y_data, 3)
y_p3 = np.polyval(p3, x)

# polynomial fit of degree 5
p5 = np.polyfit(x_data, y_data, 5)
y_p5 = np.polyval(p5, x)

#plotting
plt.plot(x_data, y_data, 'o')
plt.plot(x, y_p3, '-')

plt.plot(x, y_p5, ':')
plt.ylim(-3,3)

plt.legend(['data', 'polyfit3', 'polyfit5'])

Out[4]:
<matplotlib.legend.Legend at 0x7efcadbbb518>