In [1]:
%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 [27]:
data=np.load('decay_osc.npz')
tdata=data['tdata']
ydata=data['ydata']
dy=data['dy']
In [32]:
tdata,ydata,dy
Out[32]:
In [34]:
plt.plot(tdata,ydata)
Out[34]:
In [35]:
plt.errorbar?
In [36]:
plt.errorbar(tdata,ydata,dy,fmt='k.')
Out[36]:
In [ ]:
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 [40]:
def model(t,A,o,l,d):
return A*np.exp(-l*t)*np.cos(o*t)+d
In [47]:
theta_best,theta_cov=opt.curve_fit(model,tdata,ydata,np.array((6,1,1,0)),dy,absolute_sigma=True)
print('A = {0:.3f} +/- {1:.3f}'.format(theta_best[0], np.sqrt(theta_cov[0,0])))
print('omega = {0:.3f} +/- {1:.3f}'.format(theta_best[1], np.sqrt(theta_cov[1,1])))
print('lambda = {0:.3f} +/- {1:.3f}'.format(theta_best[2], np.sqrt(theta_cov[2,2])))
print('delta = {0:.3f} +/- {1:.3f}'.format(theta_best[3], np.sqrt(theta_cov[3,3])))
In [53]:
tfit=np.linspace(0,20,100)
A,o,l,d=theta_best
yfit=A*np.exp(-l*tfit)*np.cos(o*tfit)+d
plt.plot(tfit,yfit)
plt.plot(tdata,ydata,'k.')
plt.xlabel('time')
plt.ylabel('y')
plt.title('Decaying Oscillator')
plt.axhline(0,color='lightgray')
Out[53]:
In [ ]:
assert True # leave this cell for grading the fit; should include a plot and printout of the parameters+errors