The n = 10 data points (ak, bk), where k = 1, 2, ..., 10 are given as below, on the right is the scatter plot of the data:
a, b
166, 54
195, 82
200, 72
260, 72
265, 90
335, 124
370, 94
450, 118
517, 152
552, 132
Figure 1
Use least square line to answer the following questions where necessary:
a - Find the coefficients c1 and c2 of a linear function f(x) = c1 + c2x such that mean squared error J = (1/n) ∥ f(a) − b ∥2 is minimized.
b - Redo question a and find the c1 , c2 and c3 of the function g(x) = c1 + c2x + c3x2 so that the squared error J_1 = (1/n) ∥ g(a) − b ∥2 . Compare the value of J and J_1.
c - Draw the function f(x) and g(x) on top Figure 1
What I have tried:
#definition of the function
def myfunc(x, a, b, c):
return a + b * np.cos(x - c)
#sample data
x_data = [166, 195, 200, 260, 265, 335, 370,450,517,552]
y_data = [54, 82, 72, 72, 90, 124,94,118,152,132]
#the actual curve fitting procedure, a, b, c are stored in popt
popt, _pcov = curve_fit(myfunc, x_data, y_data)
print(popt)
print(np.degrees(popt[2]))
#the rest is just a graphic representation of the data points and the fitted curve
from matplotlib import pyplot as plt
#x_fit = np.linspace(-1, 6, 1000)
y_fit = myfunc(x_data, *popt)
plt.title("Answer to the question NO. 1(a)")
plt.plot(x_data, y_data, "ro")
plt.plot(x_data, y_fit, "b")
plt.xlabel(r'$\theta$ (degrees)');
plt.ylabel(r'$f(\theta)$');
plt.legend()
plt.show()