In [57]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
For this problem you are given a raw dataset in the file decay_osc.npz. This file contains three arrays:
tdata: an array of time valuesydata: an array of y valuesdy: the absolute uncertainties (standard deviations) in yYour job is to fit the following model to this data:
$$ y(t) = A e^{-\lambda t} \cos{\omega t + \delta} $$First, import the data using NumPy and make an appropriately styled error bar plot of the raw data.
In [58]:
A=np.load('decay_osc.npz')
In [59]:
tdata = A['tdata']
ydata= A['ydata']
dy = A['dy']
In [60]:
tdata, ydata, dy
Out[60]:
In [61]:
plt.figure(figsize=(10,5))
plt.scatter(tdata,ydata)
plt.errorbar(tdata, ydata, dy,fmt='.k', ecolor='lightgray')
plt.box(False)
plt.xlabel('t')
plt.ylabel('y')
plt.title('Decay Data')
Out[61]:
In [62]:
assert True # leave this to grade the data import and raw data plot
Now, using curve_fit to fit this model and determine the estimates and uncertainties for the parameters:
curve_fit to get a good fit.absolute_sigma=True.
In [63]:
def exp_model(t, A, B,omega,dl):
return A*np.exp(-B*t)*np.cos(omega*t) + dl
In [64]:
theta_best, theta_cov = opt.curve_fit(exp_model, tdata, ydata, absolute_sigma=True)
In [65]:
print('A = {0:.3f} +/- {1:.3f}'.format(theta_best[0], np.sqrt(theta_cov[0,0])))
print('B = {0:.3f} +/- {1:.3f}'.format(theta_best[1], np.sqrt(theta_cov[1,1])))
print('omega = {0:.3f} +/- {1:.3f}'.format(theta_best[2], np.sqrt(theta_cov[2,2])))
print('dl = {0:.3f} +/- {1:.3f}'.format(theta_best[3], np.sqrt(theta_cov[3,3])))
In [67]:
yfit= exp_model(tdata,theta_best[0],theta_best[1],theta_best[2],theta_best[3])
plt.figure(figsize=(15,5))
plt.scatter(tdata,ydata,color='black')
plt.errorbar(tdata, ydata, dy,fmt='.k', ecolor='lightgray')
plt.plot(tdata,yfit)
plt.box(False)
plt.title('Best Fit Exp Model')
plt.ylabel('ydata')
plt.xlabel('tdata')
Out[67]:
In [44]:
assert True # leave this cell for grading the fit; should include a plot and printout of the parameters+errors
In [ ]: