PHY113 Python Lab (Exercise 7)

Here’s the solution:

# Exercise 7: Nonlinear fit to Radioactive Decay
def expfit(t,N0,tau):
    return N0*exp(-t/tau)

popt,pcov = curve_fit(expfit, t, N, sigma=dN, p0=(200,100))
sigma = sqrt(diag(pcov))

Nfit = popt[0]
dNfit = sigma[0]
tau = popt[1]
dtau = sigma[1]

xfit = linspace(0, 100, 100) 
yfit = expfit(xfit,Nfit,tau)

# Plot Data
errorbar(t, N, fmt='o',label='Data',yerr=dN)
plot(xfit,yfit, label='$\chi^2$ Fit')
xlabel("time [days]")
ylabel("N")

# Add Legend
legend(loc='best') # best location to avoid hiding data
# Save figure as png file with 300dpi
savefig('DecayLinearisedFit.png', dpi=300, format='png', bbox_inches='tight')

print "Initial Activity:",Nfit,"+/-",dNfit,"decays/day"
print "Half-Life:",tau,"+/-",dtau,"days"

Everything here should by now be familiar (only the physics differ a bit, refer to the script), and you can see an example of a full working script here.

You have now joined the ranks of “the-physicists-who-code-without-semi-colons”. Congratulations.

Monty Python ~ We're not only proud of that, we're smug about it

comments powered by Disqus