# importing the module
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# data points -
xd = np.array([-8.0, -7.0, -6.0, -5.0, -4.0, -3.0,
-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0])
yd = np.array([13.6, 11.1, 12.0, 14.9, 13.7, 16.1,
19.6, 17.0, 15.3, 18.4, 14.8, 11.6,
10.2, 8.9, 9.1, 3.1, 1.1])
# cosine function
def fcos(p, q, r):
return q*np.cos(r*p)
# Extracting x,y values
# p0 - initial guess
x, y = curve_fit(fcos, xd,
yd, p0=[19, 0.1])
print(x, y)
# calling the function
fit_c = fcos(xd, x[0], x[1])
# plotting the graph
plt.plot(xd, yd, 'o', label='data')
plt.plot(xd, fit_c, '-', label='fit')