In: Computer Science
x_data = 0.40370634,0.79154934,0.93860614,1.03359578,1.10996586,1.37043231,1.48039966,1.48400251,2.0711751,2.20654611,2.44205594,2.59208994,2.89918905,3.05871931,3.14393954,3.69220148,3.82953928,4.35366153,4.39968516,4.59305454
y_data = 0.84011548,1.78884721,1.99787135,2.21465316,2.37885978,2.94376105,3.24680522,3.23332286,3.91964859,3.95421123,3.98672869,3.91397619,3.68430662,3.35694299,3.26097864,2.15150802,1.85306748,0.80989029,0.72714957,0.51251446
As a starting point, let's see if we can fit a simple polynomial model to this mysterious data.
✅ Question 2.1: (3 pts) Using the NumPy polyfit function, fit the data with a second order polynomial, which has the form ?=?(?)=?0?2+?1?+?2 . The parameters, ?0 , ?1 and ?2 , will be determined by the polyfit function. Once you're created the fit, use poly1d to create a function based on your fit and use this new function to plot the data together with the best fit second order polynomial model. Include a legend to make it clear what information represents the data and what information represents the best fit. -- Using Python
Code with comments
-------------------------
import numpy as np
import matplotlib.pyplot as plt
x_data = np.array([0.40370634, 0.79154934, 0.93860614, 1.03359578, 1.10996586, 1.37043231, 1.48039966, 1.48400251, 2.0711751, 2.20654611,
2.44205594, 2.59208994, 2.89918905, 3.05871931, 3.14393954, 3.69220148, 3.82953928, 4.35366153, 4.39968516, 4.59305454])
y_data = np.array([0.84011548, 1.78884721, 1.99787135, 2.21465316, 2.37885978, 2.94376105, 3.24680522, 3.23332286, 3.91964859,
3.95421123, 3.98672869, 3.91397619, 3.68430662, 3.35694299, 3.26097864, 2.15150802, 1.85306748, 0.80989029, 0.72714957, 0.51251446])
px = np.polyfit(x_data, y_data, 2) # fit a polynomial
fun = np.poly1d(px) # create function
plt.plot(x_data, y_data, label='Original Data') # plot data
plt.plot(x_data, fun(x_data), label='Fitted Data') # plot data
plt.legend()
plt.title('Fitting a degree 2 polynomial')
plt.show()