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.
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
# 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'])
https://www.youtube.com/watch?v=970im6yAmhE code has been modified