程序代写代做 go algorithm clock graph interpreter Part II Computa􏰅onal Physics Exercises

Part II Computa􏰅onal Physics Exercises
David Buscher 􏰆􏰇􏰈 v􏰉.􏰊 – 􏰉􏰇􏰉􏰇/􏰇􏰆/􏰉􏰆
Contents
􏰆 Introduc􏰅on 􏰉
􏰉 Assessment 􏰋
􏰉.􏰆 Pigeonholes ………………………….. 􏰋 􏰉.􏰉 Codequality………………………….. 􏰌
􏰋 Ge􏰍ng started 􏰌
􏰋.􏰆 UsingtheLinuxMCS……………………… 􏰌 􏰋.􏰉 Se􏰍ngupyourscipyenvironment ………………. 􏰊 􏰋.􏰋 Se􏰍ngupyourworkspace…………………… 􏰊 􏰋.􏰌 Runningyourprogram …………………….. 􏰊 􏰋.􏰊 Plo􏰍ngyourresults………………………. 􏰈 􏰋.􏰈 Examplecode …………………………. 􏰈
􏰌 Exercise 􏰆: Integra􏰅on 􏰈
􏰌.􏰆 Goal………………………………. 􏰈 􏰌.􏰉 BackgroundTheory………………………. 􏰎 􏰌.􏰋 Tasks ……………………………… 􏰎 􏰌.􏰌 Stepbystepguide:Monte-Carlointegra􏰅on . . . . . . . . . . . . . 􏰏 􏰌.􏰊 Step by step guide: Numerical Integra􏰅on with . . . . . . . . 􏰆􏰇
􏰊 Exercise 􏰉: The Driven Pendulum 􏰆􏰇
􏰊.􏰆 Goal………………………………. 􏰆􏰇 􏰆

􏰊.􏰉 Physics…………………………….. 􏰆􏰇 􏰊.􏰋 Tasks ……………………………… 􏰆􏰆 􏰊.􏰌 Hints ……………………………… 􏰆􏰉
􏰈 Exercise 􏰋A: Helmholtz Coils 􏰆􏰋
􏰈.􏰆 Goal………………………………. 􏰆􏰋 􏰈.􏰉 Physics…………………………….. 􏰆􏰋 􏰈.􏰋 Tasks ……………………………… 􏰆􏰌 􏰈.􏰌 Hints ……………………………… 􏰆􏰊
􏰎 Exercise 􏰋B: Diffrac􏰅on by the FFT 􏰆􏰊
􏰎.􏰆 Goal………………………………. 􏰆􏰊 􏰎.􏰉 Physics…………………………….. 􏰆􏰊 􏰎.􏰋 Tasks ……………………………… 􏰆􏰎 􏰎.􏰌 Hints ……………………………… 􏰆􏰐
􏰆 Introduc􏰅on
These exercises are designed to help you learn some , understand some physics and learn a li􏰑le more about numerical programming. You should a􏰑empt the exercises one per week, in the order given. Demonstrators will be on hand in the MCS to assist.
The speed at which people can program varies widely. It even varies for individuals day by day — all programmers will sympathise with how much 􏰅me can be wasted trying to fix an obscure bug. So do keep an eye on the clock, and do seek assistance. Talk to your colleagues so you can share experience and spot each others’ mistakes. The goal of the exercises is for you to learn – and you can only do this by experience.
Each exercise is split into tasks. The core task or tasks are ones that I hope you will all be able to achieve in the class in the 􏰅me available. If you hand in a working solu􏰅on to this you will get approximately 􏰈􏰇–􏰎􏰇% of the credit for the exercise. There is also one or more supplementary tasks per exercise, which take the problem further, or in a different direc􏰅on. I hope that many of you will achieve some or most of these, and they count for the remaining frac􏰅on of the credit.
I have given structured hints to each problem. In addi􏰅on, you should browse the code examples available on the MCS computers (see §􏰋.􏰈), and, importantly consult the relevant documenta􏰅on for the libraries such as and — finding and learning from online documenta􏰅on and code examples is an important skill. There are some star􏰅ng links from the course web-page or just use a search engine.
􏰉

􏰉 Assessment
Over the 􏰌 weeks you should carry out three exercises: Exercise 􏰆, Exercise 􏰉, and either Exercise 􏰋A or 􏰋B. The marks available are a maximum of 􏰈 for exercises 􏰆 and 􏰉, and a maximum of 􏰐 for exercise 􏰋A or 􏰋B, for a total of 􏰉􏰇 marks.
You should upload your solu􏰅on to the exercises to your pigeonhole (see below). The deadline is posted on the course web site and the TiS. You are encouraged to submit your work as soon as it is in a reasonable state, and move on. So don’t spend too much 􏰅me on the tasks, but don’t spend too li􏰑le 􏰅me either.
The exercises suggest what to submit: normally this is
􏰆. Source code file: normally this will be just one or two files (or files). Python files should run without problem on the MCS using ). If using , your files should compile and link on the MCS system (I will assume that the files require the Gnu Science Library () and and libraries to link).
􏰉. a text file which describes very briefly what you did, any major problems, and men􏰅ons any numerical answers required and describes any accompanying plots. An alterna􏰅ve is to submit a PDF file, called which contains the text men􏰅oned above, but can also include the plots men- 􏰅oned below. Do not submit Microso􏰒 Word files or similar — only plain text or PDF files will be considered.
􏰋. PDF plots illustra􏰅ng the problem. See §􏰋.􏰊 on how to plot in PDF format. Your plots can be included in the file if desired, in which case addi􏰅onal plot files are not required. Remember to annotate your graph axes appropriately.
Please be aware of the following:
• You must submit Python files and not files (Jupyter notebook files). The Jupyter notebook is a good environment for experimen􏰅ng with Python, but for this course, you must submit your work as a standard Python program.
• Please do not submit data files or C􏰓􏰓 executables to the pigeonholes. Any files (with the excep􏰅on of PDF files) larger than 􏰆 MB will be deleted without looking at them.
􏰉.􏰆 Pigeonholes
You are required to submit your work electronically to what I have called your pi- geonhole. You should upload your answer to each exercise to its own directory. These directories should have the names

􏰋


and either or
respec􏰅vely, where should be subs􏰅tuted with your own crsid.
Important: Let me know if you have problems using your pigeonhole or if it is missing. If you find you can’t delete files once uploaded, and need to add a new version, just upload a new version with a number at the end, e.g. Or you can create a whole new directory in the pigeonhole and put a whole new solu􏰅on there; perhaps call it or something like that.
􏰉.􏰉 Code quality
In the first two exercises, the main emphasis of the marking will be on successful comple􏰅on of the tasks. In the last exercise a percentage of the marks will be given for code quality (this will also be true for the op􏰅onal project). High-quality code will include at minimum:
• Structured code: tasks broken down into sensible func􏰅ons;
• Meaningful func􏰅on names;
• Meaningful variable names (this is less important than for naming func􏰅ons:
single-le􏰑er variable names can be meaningful if the meaning can be inferred
from context, e.g. loop counters);
• Appropriate levels of commen􏰅ng (at minimum iden􏰅fying what each func-
􏰅on does);
• Sensible use of whitespace to indicate code structure.
Remember, code quality is important because (a) it helps to make the code easier to understand and debug for the person wri􏰅ng the code and (b) it makes the code easier to understand and debug for others who may have to modify the program later on.
Wri􏰅ng high-quality code is somewhat like wri􏰅ng high-quality prose or mathe- ma􏰅cs: clearly structuring and explaining your thoughts for someone else can help clarify your own thinking, and this clear explana􏰅on is what code quality is all about.
􏰋 Ge􏰍ng started
􏰋.􏰆 Using the Linux MCS
If you are not familiar with using the MCS Linux system, I strongly recommend that
you read the relevant sec􏰅ons of the Part IB compu􏰅ng tutorial available at 􏰌

􏰉􏰇􏰆􏰏 (this docu- ment is also linked from the Part II Computa􏰅onal Physics course website), specif- ically sec􏰅on 􏰌.􏰉 about logging in and using a text editor, and the appendix with a list of useful Unix/Linux commands.
􏰋.􏰉 Se􏰍ng up your scipy environment
Unfortunately the Python setup on the MCS is not updated very frequently, and par􏰅cularly the library is quite out-of-date. The best way to avoid issues arising from this is to install your own copy of scipy, by typing the following into the terminal at the command prompt:

This could result in a fair amount of ac􏰅vity on the screen before returning you to a command prompt. You can then verify that you have a recent version of scipy by typing the following command into your terminal:

This prints out the version number; if your version number is at least , then
the examples from the lectures should all work. 􏰋.􏰋 Se􏰍ng up your workspace
I strongly recommend using a new directory for each project you do — this will make it much easier to look a􏰒er your files. To do this, use the UNIX command. So for example from your home directory:

Then start work in this directory; next week, make etc. 􏰋.􏰌 Running your program
You can use a text editor such as , or to type in your code. Once you have saved it in, say, you can run it by typing

andlookingattheresults.Notethatifinsteadyouweretotype , this would invoke the 􏰉 interpreter. In this course we are emphasising the use of 􏰋, which is very similar to, but not the same as, 􏰉.
􏰊

􏰋.􏰊 Plo􏰍ng your results
It’s o􏰒en convenient to use to write output from a program. You can catch this in a file using UNIX re-direc􏰅on:

You can then read the answers back in to a separate program for plo􏰍ng. Alter- na􏰅vely, you can skip saving the results to a file and plot the results from the same program which calculates the data. This is ok as long as the calcula􏰅on 􏰅me is short (less than a few seconds): otherwise when you make a mistake in the plo􏰍ng you need to wait for the calcula􏰅on to repeat.
Remember to hand in plots in PDF format. Be sure to add cap􏰅ons for the axes and a 􏰅tle. Here is a simple Python program which plots a sine func􏰅on with axes and saves it as a PDF file.






􏰋.􏰈 Example code
There are example programs which might be useful in the directory:
.
Remember the command which searches through files for text — you
could use this to search files in this directory for example.
􏰌 Exercise 􏰆: Integra􏰅on
􏰌.􏰆 Goal
To learn how to evaluate integrals numerically, using (a) a self-wri􏰑en Monte-Carlo
method and (b) a general purpose integrator from .
􏰈

􏰌.􏰉 Background Theory
Suppose we have a func􏰅on f of n parameters which we can regard as an n- dimensional vector r. We want to integrate this over a mul􏰅dimensional volume V. We can es􏰅mate this by taking N samples distributed at random points ri through- out the volume V, as follows:
􏰖
where 􏰂 􏰆 N−􏰆
fdV≈ V⟨f⟩±σ (􏰆)
⟨f⟩ ≡ N
􏰀⟨f􏰉⟩ − ⟨f⟩􏰉 􏰁􏰆/􏰉
f(ri) (􏰉) σ≈V N (􏰋)
and
with 􏰂
i=􏰇
􏰆 N−􏰆
⟨f􏰉⟩ ≡ N f􏰉(ri) (􏰌)
i=􏰇
Note that the error es􏰅mate in equa􏰅on (􏰋) is not guaranteed to be very good, and is not Gaussian-distributed: treat it as indica􏰅ve only of the error. In this exercise you will es􏰅mate the error by a robust Monte-Carlo approach and compare it with the theore􏰅cal error.
􏰌.􏰋 Tasks
Core Task 􏰆 : Write a program to find an approximate value of this integral and an associated error es􏰅mate:
􏰈 􏰖 s􏰖 s􏰖 s􏰖 s􏰖 s􏰖 s􏰖 s􏰖 s
􏰆􏰇 sin(x􏰇+x􏰆+x􏰉+x􏰋+x􏰌+x􏰊+x􏰈+x􏰎)dx􏰇dx􏰆dx􏰉dx􏰋dx􏰌dx􏰊dx􏰈dx􏰎
􏰇􏰇􏰇􏰇􏰇􏰇􏰇􏰇 where
s=π 􏰐
Show that the error in the integral falls off as N−􏰆/􏰉 where N is the number of Monte-Carlo samples. In this task you should es􏰅mate the error on the value for a given N from the standard devia􏰅on of several independent es􏰅mates, and plot a suitable graph.
(In case you are wondering, there is an analy􏰅c answer in this case, but that’s not the point! The answer is in fact 􏰆􏰇􏰈 ×(􏰎􏰇−􏰆􏰈 sin(π/􏰐)+􏰊􏰈 sin(π/􏰌)−􏰆􏰆􏰉 sin(􏰋π/􏰐)) ≈ 􏰊􏰋􏰎.􏰆􏰐􏰎􏰋􏰌􏰆􏰆.)
using Monte-Carlo techniques.
􏰎

Upload to the course pigeonhole: Source code ( or ), relevant graph- ical plots, and a containing a couple of sentences summarising what you managed to achieve, and the integral’s value and the error es􏰅- mate. Specifically, include your integral value, error es􏰅mate and N value for the largest value of N for which you can compute results in a reasonable amount of 􏰅me.
Note: if you are wri􏰅ng in , then wri􏰅ng a vectorised program will allow you to reach much higher values of N than if you code all the loops explicitly. Try this if you have 􏰅me.
Core Task 􏰉 : Write a program to evaluate the Fresnel integrals accurately using a standard integra􏰅on rou􏰅ne from the , and use this to make a plot of the Cornu spiral using . Do not use a Monte-Carlo rou􏰅ne — they are not effi- cient for low-dimensional integrals — instead use a standard quadrature technique. One version of the Fresnel integrals can be wri􏰑en
􏰖u 􏰀πx􏰉􏰁 C(u)=􏰇cos 􏰉 dx
􏰖u 􏰀πx􏰉􏰁 S(u)=􏰇sin 􏰉 dx
Supplementary Task 􏰆 Compare your error derived from the sca􏰑er of your Monte- Carlo simula􏰅ons with the theore􏰅cal error es􏰅mate given by equa􏰅on (􏰋), using a suitable plot.
Supplementary Task 􏰉 : Use the previous work to calculate and plot the diffrac- 􏰅on pa􏰑ern of a slit of width d = 􏰆􏰇 cm illuminated at normal incidence by plane monochroma􏰅c waves of wavelength λ = 􏰆 cm. The pa􏰑ern is observed on a plane normal to the slit and the incoming waves. Calculate the pa􏰑ern when the screen is at distances D = 􏰋􏰇, 􏰊􏰇 and 􏰆􏰇􏰇 cm from the slit. Plot both the rela􏰅ve amplitude and the phase of the pa􏰑ern. (The absolute amplitude and phase are not important here).
Physics reminder: the complex amplitude in the near field on the axis of an open slit
Upload to the course pigeonhole: source code, relevant plots.
Upload to the course pigeonhole: source code, relevant plot.
is given by
􏰖 x􏰆 􏰉 􏰉
Ψ ∝ (cos(πx /(λD)) + i sin(πx /(λD))) dx x􏰇
􏰐

so you can use the Fresnel integrals directly scaling the length dimensions by 􏰗􏰉/(λD). This result holds good for D ≫ 􏰔d􏰌 􏰕􏰆/􏰋, And the Fraunhofer limit applies when
D ≫ d􏰉 . λ λ
Upload to the course pigeonhole: source code, relevant plot.
􏰌.􏰌 Step by step guide: Monte-Carlo integra􏰅on
􏰆. The first goal is to write a func􏰅on that returns an es􏰅mate of the integral’s value using N sample points using Equa􏰅on 􏰆. It is sensible to make N an argument (perhaps the only argument) of this func􏰅on, and make the func􏰅on return the value of the es􏰅mate. This func􏰅on can then be called over and over to get es􏰅mates of the integral.
􏰉. In , the value of π is held in . You can simplify your life a li􏰑le byhavinga statementatthestartofyourcode,then you only need to type therea􏰒er to get its value.
􏰋. You will need to be able to generate random points in 􏰐-dimensional (or gen- erally n−dimensional) space. Use the random number genera- tors for this. Look in the example code from the lectures and in the examples directory to see how this can be done.
􏰌. The basic logic you require now is to loop over increasing values of N; and for each N value, es􏰅mate the integral several 􏰅mes, and find a best value and error by looking at the mean and spread of es􏰅mates returned. How big should N be? Experiment! And think about the error you might want to achieve. To debug your code, a small value is good, but when you are sure things are working well you should set N to be as large as possible.
How many samples can you compute in a few minutes on the MCS? Does this makes sense, supposing the computer clock speed is about 􏰋 GHz say? In , your code may run orders of magnitude faster if you think about how to vectorise your code, in other words use func􏰅ons such as to act on a whole array of numbers in a single func􏰅on call.
􏰊. For a given N, es􏰅mate the integral nt 􏰅mes. (nt = 􏰉􏰊 might be a sensible choice). (Make sure your random numbers are different for each trial – they will be as long as you do not re-seed the random number generator). From these nt independent es􏰅mates you can es􏰅mate the best value (from the mean of the values) and the error in the value (from the rms of the values). You could either store these independent samples in an array so that you can compute mean and standard devia􏰅ons at the end, or you can compute the mean and mean square values as you go through your loop over nt.
􏰈. Make your program output the es􏰅mates and errors, and plot them. For the longer runs it is likely best to save the results to a file and read them back in to a separate plo􏰍ng program.
You could perhaps use the func􏰅on in to illustrate
􏰏

error bars. Also don’t forget the logarithmic plo􏰍ng capabili􏰅es in
for example.
􏰎. Save your plot to a file for submission to your pigeonhole.
􏰌.􏰊 Step by step guide: Numerical Integra􏰅on with

􏰆. You will need to choose a rou􏰅ne to do the integra􏰅on. The func􏰅on is a good general purpose integrator. Example code is available online: search for “scipy numerical integra􏰅on examples”.
􏰉. Write suitable func􏰅ons that evaluate the two integrands. Make sure the func􏰅ons have the correct parameters and return value types to match the func􏰅on required by the relevant integra􏰅on func􏰅on.
􏰋. Evaluatetheintegralsforvariousvaluesofsandusetoplotthespiral.
􏰌. Plo􏰍ng the diffrac􏰅on pa􏰑ern should now be straigh􏰘orward.
􏰊 Exercise 􏰉: The Driven Pendulum
􏰊.􏰆 Goal
To inves􏰅gate the physics of a damped, driven pendulum by accurate integra􏰅on of its equa􏰅on of mo􏰅on.
􏰊.􏰉 Physics
The pendulum comprises a bob of mass m on a light rod of length l and swings in a uniform gravita􏰅onal field g. If there is a resis􏰅ve force equal to αv where the bob speed is v, and a driving sinusoidal couple G at frequency ΩD, we can write
m l􏰉 d􏰉θ = −m g l sin(θ) − α l dθ + G sin(ΩDt) (􏰊) dt􏰉 dt
Rearranging:
where we have defined q ≡ α/(m l) and F ≡ G/(m l􏰉).
d􏰉θ = −g sin(θ) − q dθ + F sin(ΩDt) (􏰈) dt􏰉 l dt
For the purposes of this exercise, take l = g, so the natural period for small os- cilla􏰅ons should be 􏰉π seconds. Also let the driving angular frequency be Ω = 􏰉/􏰋 rad s−􏰆. This leaves q and F, and the ini􏰅al condi􏰅ons, to be varied. For all of these problems, we will start the pendulum from rest i.e. θ ̇ = 􏰇 at t = 􏰇, but we will vary the ini􏰅al displacement θ􏰇. The parameter space to explore then is in the three values q, F and θ􏰇.
􏰆􏰇

􏰊.􏰋 Tasks
Core Task 􏰆 First re-write this second-order differen􏰅al equa􏰅on Equa􏰅on 􏰈 as a pair of linked first-order equa􏰅ons in the variables y􏰇 = θ and y􏰆 = ω = θ ̇ . Now write a program that will integrate this pair of equa􏰅ons using a suitable algorithm, for example a 􏰌th order Runge-Ku􏰑a technique, from a given star􏰅ng point θ = θ􏰇 and ω = ω􏰇 at t = 􏰇. I recommend using rather than implemen􏰅ng your own Runge-Ku􏰑a technique. The program should write out line by line the values of t, θ, ω and total energy at frequent enough intervals to follow the evolu􏰅on of the equa􏰅ons. If your files get big, you should modify the program to write out the results less frequently.
Test the code by se􏰍ng q = F = 􏰇 and star􏰅ng from (θ􏰇,ω􏰇) = (􏰇.􏰇􏰆,􏰇.􏰇), and plo􏰍ng the solu􏰅on for 􏰆􏰇, 􏰆􏰇􏰇, 􏰆􏰇􏰇􏰇…natural periods of oscilla􏰅on. Overlay on your plot the expected theore􏰅cal result for small-angle oscilla􏰅ons — make sure they agree!
Test how well your integrator conserves energy: run the code for, say, 􏰆􏰇,􏰇􏰇􏰇 os- cilla􏰅ons and plot the evolu􏰅on of energy with 􏰅me.
Now find how the amplitude of undriven, undamped oscilla􏰅ons depends affects the period. Plot a graph of the period T versus θ􏰇 for 􏰇 < θ􏰇 < π. In your wri􏰑en answer file, state the period for θ􏰇 = π/􏰉. Core task 􏰉 Now turn on some damping, say q = 􏰆, 􏰊, 􏰆􏰇, plot some results, and check that the results make sense. Now turn on the driving force, leaving q = 􏰇.􏰊 from now on, and inves􏰅gate with suitable plots the behaviour for F = 􏰇.􏰊, 􏰆.􏰉, 􏰆.􏰌􏰌, 􏰆.􏰌􏰈􏰊. What happens to the period of oscilla􏰅on? Note that the period of oscilla􏰙on is best observed in the angular velocity rather than angular posi􏰙on, to avoid problems with wrap-around at ±π. Supplementary task 􏰆 Inves􏰅gate the sensi􏰅vity to ini􏰅al condi􏰅ons: compare two oscilla􏰅ons, one with F = 􏰆.􏰉, θ􏰇 = 􏰇.􏰉 and one with F = 􏰆.􏰉, θ􏰇 = 􏰇.􏰉􏰇􏰇􏰇􏰆. Integrate for a ’long 􏰅me’ to see if the solu􏰅ons diverge or stay the same. Upload to the course pigeonhole: Source code, containing a couple of sentences summarising what you managed to achieve, and the value of the period for θ􏰇 = π/􏰉; include an appropriately-scaled plot showing how well energy is conserved in at least one case and a plot of period versus amplitude. Upload to the course pigeonhole: Source code, a sentence or two in the explaining what you see in the solu􏰅ons, and illustra􏰅ve plots of the displacement θ and the angular velocity dθ versus 􏰅me. dt 􏰆􏰆 Upload to the course pigeonhole: Source code, a sentence or two in the explaining what you see in the solu􏰅ons, and illustra􏰅ve plots of the behaviour. Supplementary Task 􏰉 Try plo􏰍ng angle versus angular speed for various solu- 􏰅ons, to compare the type of behaviour in various regimes: you can inves􏰅gate chao􏰅c behaviour using this simple code — have a look in the books or a web site for examples. There is a nice demo for example at . There’s lots more physics to be explored here — experiment if you have 􏰅me! 􏰊.􏰌 Hints 􏰆. Hopefully rewri􏰅ng the equa􏰅on as 􏰉 ODEs is straigh􏰘orward: if not, ask! 􏰉. I recommend that you use the fourth-order Runge-Ku􏰑a integrator for ex- ample the func􏰅on, rather than wri􏰅ng your own. 􏰋. Both techniques are best done by first wri􏰅ng a func􏰅on that evaluates the deriva􏰅ves of the ODEs at a given 􏰅me given the current values of the vari- ables. You can look at the example programs in or which solve the spinning ring problem discussed in lectures. You can perhaps adapt some of that code if you get stuck. 􏰌. Use the ”>” redirect symbol on the command line to send your output to a file. It is probably not necessary to write out every 􏰅me step used by the integrator (this is not a problem with the integrator as it only returns values at the ordinates you choose): you may want only to print out every, say, 􏰆􏰇th or 􏰆􏰇􏰇th value.
􏰊. A note on plo􏰍ng: you may want to write out a text file containing columns of data — perhaps 􏰅me, angle, angular speed, energy. You can then read back the results into a separate Python program and plot them over different 􏰅me spans.
􏰈. To find the period versus amplitude rela􏰅onship, a simple (and just about acceptable) way is to measure the period off a suitable plot, and do this for several values of θ􏰇. However, it is much be􏰑er to alter your code to es􏰅mate the period directly. You can then loop over θ􏰇 values and plot the period versus amplitude rela􏰅on. Two obvious approaches spring to mind. First, you can find when θ first goes nega􏰅ve. This is when the 􏰅me is approximately T/􏰌 where T is the period. How accurate would this result be? You could also find several zero crossings by considering when y changes sign or becomes
Upload to the course pigeonhole: Source code, a sentence or two in the explaining what you see in the solu􏰅ons, and illustra􏰅ve plots of the behaviour.
􏰆􏰉

exactly zero a􏰒er a step is taken; by coun􏰅ng many such zero crossings and
recording the 􏰅me between them you can get a more accurate value for T. 􏰎. Note that you need to think about what happens when the pendulum goes “over the top” and comes down the other side — you need to think about the 􏰉π ambigui􏰅es involved, and what this means in terms of the “period” of an
oscilla􏰅on.
􏰈 Exercise 􏰋A: Helmholtz Coils
􏰈.􏰆 Goal
Write a program to calculate the magne􏰅c field caused by Helmholtz coils. Check your solu􏰅on agrees with the on-axis analy􏰅cal result. Inves􏰅gate with suitable plots the uniformity of the field near the centre of the system.
􏰈.􏰉 Physics
The physics of this exercise is straigh􏰘orward: you will all know that a small length
of wire dl carrying a current I creates a magne􏰅c field
dB= μ􏰇 Idl∧r (􏰎)
􏰌π r􏰋
at a loca􏰅on r with respect to the current element. So by breaking up any wire into short elements we can simply add up all the contribu􏰅ons to find the total magne􏰅c field. Note that in this problems you are expected to do simply this. There are of course more accurate ways to compute integrals numerically — but this exercise is more about how to organise your code than how to evaluate integrals to high accuracy.
􏰆􏰋

Recall that the axial field on the axis of a single coil is given by
B = μ􏰇 I R􏰉 (􏰐)
􏰉(R􏰉 + x􏰉)􏰋/􏰉
Helmholtz coils produce a fairly uniform field close to the centre of the system. They consist of two co-axis coils carrying parallel and equal currents I. The separa- 􏰅on D of the coils centres is set equal to their radius R. For coils with axes aligned with the x axis we can place the coil centres at (±(R/􏰉), 􏰇, 􏰇). For the purposes of this problem set R = 􏰆.􏰇 m and it is convenient to set the current so it has a (very large!) value of (􏰆/μ􏰇) amps, to get easy to interpret numbers (although somewhat high field strengths!). The field expected at the coil centres is then
B = 􏰀􏰌􏰁􏰋/􏰉 μ􏰇 I 􏰊R
􏰈.􏰋 Tasks
Core Task 􏰆 Write a program which computes the magne􏰅c field from a single coil of radius R = 􏰆m carrying a current I = 􏰆/μ􏰇 amps. Put the coil centre at (􏰇, 􏰇) and let the coil’s axis run in the x direc􏰅on. Calculate the field in the x − y plane. First check your field on axis (y = z = 􏰇) agrees with theory by plo􏰍ng your result against the theore􏰅cal one. Then calculate the field on a x − y grid and plot your results. To compare theory with your calcula􏰅on, you should plot the difference between theory and calcula􏰅on along the x axis, as well as the actual values.
You will need to break the wire up into a series of straight line elements, and using the Biot-Savart law, you can then add up the total field. How many elements should you break your circle into? You should experiment with different values in your code. And how does the final accuracy of your calcula􏰅on depend on this value?
Core Task 􏰉 Now adapt your program to calculate the field from Helmholtz coils arranged as in the diagram. Plot the field strength near the centre. How uniform is the field? The coil centres should be set to be (±􏰇.􏰊 m, 􏰇, 􏰇) with the coils’ axes poin􏰅ng in the x direc􏰅on. Calculate and plot the magne􏰅c field strength in the vicinity of (􏰇, 􏰇, 􏰇). Show that the field is quite uniform in this region. To quan􏰅fy this uniformity, find the maximum percentage devia􏰅on of the field magnitude from that at (􏰇, 􏰇, 􏰇) within a cylinder which has diameter 􏰆􏰇cm, length 􏰆􏰇cm, and is coaxial with the coils. The centre of the cylinder should be at (􏰇, 􏰇, 􏰇). Because of the symmetry, it is of course sufficient to calculate and plot the field for z = 􏰇 i.e. plot B(x, y, 􏰇), with x and y extending to ±􏰊cm.
Supplementary Task Extend or modify your code to inves􏰅gate the field caused by a series of N coaxial coils with uniform spacing carrying the same current. Make plots to show the effects of varying N while keeping the distance between the outermost coils constant at D = 􏰆􏰇R.
􏰆􏰌

􏰈.􏰌 Hints
There are several ways to approach this problem. Do some thinking before you start coding. First, you have to decide how to deal with the vector fields, both for the posi􏰅on and magne􏰅c field vectors. One possibility is to have three arrays represen􏰅ng the Cartesian x, y and z components of the vectors respec􏰅vely. Al- terna􏰅vely, a higher-dimensional array where the last dimension of the array is of length three may be the way forward. The choice is yours.
You then need to think about how to represent the wire. I recommend that you write a program that is general, i.e. that can calculate the field due to an arbitrary wire. You could define the wire by a set of N line segments defined by N + 􏰆 points in space, each sec􏰅on of wire running from (xi, yi, zi) to (xi+􏰆, yi+􏰆, zi+􏰆), i.e. from ri to ri+􏰆 using vectors.
You can now write a func􏰅on that calculates the contribu􏰅on dB from each sec􏰅on using equa􏰅on Equa􏰅on 􏰎, and add them up to find the total field of the wire. You need to evaluate the cross product of course. Be careful close to the wires where r gets small.
Now you need to create a wire which represents a single coil suitably, and evaluate the field it produces by stepping over a 􏰉-d grid of points in the (x, y) plane.
You can plot the 􏰉-dimension varia􏰅on of the magnitude of the field as an image using the func􏰅on from . You could also experiment with plo􏰍ng the vector field using func􏰅on. There can be a lot of data, so it may be simplest in some cases to compute your results and plot them in the same program, avoiding the complexity of wri􏰅ng out and then reading back in the data.
􏰎 Exercise 􏰋B: Diffrac􏰅on by the FFT
􏰎.􏰆 Goal
Write a program to calculate the near and far-field diffrac􏰅on pa􏰑erns of an ar- bitrary one-dimensional complex aperture using the Fast Fourier Transform tech- nique. Test this program by using simple test apertures (a slit) for which the theoret- ical pa􏰑ern is known. Inves􏰅gate more complicated apertures for which analy􏰅cal results are difficult to compute.
􏰎.􏰉 Physics
Plane monochroma􏰅c waves, of wavelength λ, arrive at normal incidence on an
aperture, which has a complex transmi􏰑ance A(x). The wave is diffracted, and the 􏰆􏰊

Figure 􏰆: Geometry for diffrac􏰅on calcula􏰅on
pa􏰑ern is observed on a screen a distance D from the aperture and parallel to it. We want to calculate the pa􏰑ern when the screen is in the far-field of the aperture (Fraunhofer diffrac􏰅on) and also in the near-field (Fresnel).
Using Huygen’s construc􏰅on, we can write the disturbance at a point P on the screen, a distance y from the axis, as
ψ(y) ∝ 􏰖 A(x) exp(ikr) dx r
where k = 􏰉π/λ. We have assumed that all angles are small: x, y ≪ D
so that we are close to the straight-through axis and can therefore neglect terms like cos(θ) which appear if we are off-axis. We now expand the path length r in
powers of x/r:
r􏰉 =D􏰉 +(y−x)􏰉
y􏰉 xy x􏰉 􏰀(y−x)􏰌􏰁
r≈D+􏰉D− D +􏰉D+O D􏰋
If we now neglect the varia􏰅on in r in the denominator of the integral, se􏰍ng r ≈ D,
which is adequate for x, y ≪ D, then we can write
ψ(y)∝exp(ikD)exp􏰀iky􏰉􏰁􏰖 A(x)exp􏰀ikx􏰉􏰁exp􏰀−ikxy􏰁dx (􏰏)
D 􏰉D 􏰉D D 􏰆􏰈

The diffrac􏰅on pa􏰑ern is thus the Fourier-transform of the modified aperture func-
􏰅on A′: with
ψ(y)∝exp􏰀iky􏰉􏰁􏰖 A′(x) exp􏰀−ikxy􏰁dx (􏰆􏰇) 􏰉D D
A′(x) = exp 􏰀ikx􏰉 􏰁 A(x) (􏰆􏰆) 􏰉D
In the far-field (Franhofer limit) we have kx􏰉/(􏰉D) ≪ π so that A′ ≈ A for all values of x in the aperture where A(x) is non-zero, i.e. the familiar result
d ≫ x􏰉max . λ
The distance x􏰉max/λ is the Fresnel distance. In this case, the diffrac􏰅on pa􏰑ern is just the Fourier transform of the aperture func􏰅on.
Note that we can calculate the near-field (Fresnel) pa􏰑ern also if we include a step to modify the aperture func􏰅on according to Equa􏰅on 􏰆􏰆 before we take its Fourier transform.
Note that if we are only interested in the pa􏰑ern’s intensity, we can ignore the phase prefactor in Equa􏰅on 􏰆􏰇.
Finally, we can discre􏰅ze Equa􏰅on 􏰆􏰇, by sampling the aperture evenly at posi􏰅ons
xj
where Δ is the distance between the aperture sample posi􏰅ons xj.
􏰂N−􏰆 􏰀 −ikxj y 􏰁
ψ(y) ∝ Δ A′(xj) exp D (􏰆􏰉)
j=􏰇
One convenient defini􏰅on of the sample points in x is
xj = (j − (N/􏰉))Δ, (􏰆􏰋)
where N is the number of sample points in the aperture. Note that this defini􏰅on of the x-coordinate is equivalent to applying a coordinate transform equivalent to the “􏰚shi􏰒” opera􏰅on described in the lectures, and results in Fourier phases which are closer to zero compared to a more simple linear rela􏰅onship between xj and j.
􏰎.􏰋 Tasks
Core Task 􏰆 : Write a program that will calculate the diffrac􏰅on pa􏰑ern of a gen- eral 􏰆-dimensional complex aperture in the far field of the aperture using FFT tech- niques. The program should calculate the intensity in the pa􏰑ern across the screen, which you should plot using the correct y coordinates (in metres or microns for ex- ample). Label your coordinates.
Test this program for the specific case of a slit in the centre of an otherwise blocked aperture: take the single slit to have width d in the centre of an aperture of total
􏰆􏰎

extent L. For definiteness, use λ = 􏰊􏰇􏰇nm, d􏰛􏰆􏰇􏰇 microns, D = 􏰆.􏰇m and L =􏰊mm. Overlay on your plot the theore􏰅cal value of the intensity pa􏰑ern expected.
Core Task 􏰉 : Now calculate and plot the Fraunhofer diffrac􏰅on pa􏰑ern of a sinu- soidal phase gra􏰙ng. This gra􏰅ng is a slit of extent d = 􏰉mm, outside of which the transmission is zero. Within |x| < d/􏰉, the transmission amplitude is 􏰆.􏰇, and the phase of A is φ(x) = (m/􏰉) sin(􏰉πx/s) where s is the spacing of the phase maxima, and can be taken as 􏰆􏰇􏰇microns for this problem. For this calcula􏰅on, use m = 􏰐. The Fresnel distance d􏰉/λ is 􏰐m, so calculate the pa􏰑ern on a screen at D = 􏰆􏰇 m. What do you no􏰅ce about the resul􏰅ng pa􏰑ern? Supplementary Task : Now modify your program so that the calcula􏰅on is accu- rate even in the near-field by adding a phase correc􏰅on to the aperture func􏰅on as defined by Equa􏰅on 􏰆􏰆. Repeat your calcula􏰅ons in the previous two tasks for D = 􏰊mm for the slit, and D = 􏰇.􏰊m for the phase gra􏰅ng, and plot the results. Do the intensity pa􏰑erns look sensible? 􏰎.􏰌 Hints Recall the FFT defini􏰅on: Hj = which maps N 􏰅me-domain samples hm into N frequencies, which are • j = 􏰇 is zero frequency. • For 􏰆 ≤ n ≤ (N/􏰉), we have posi􏰅ve frequencies (j/N) × (􏰆/Δ). • For (N/􏰉) + 􏰆 ≤ j ≤ (N − 􏰆) we have nega􏰙ve frequencies which we compute as ((j/N) − 􏰆) × (􏰆/Δ). (Remember the sequences are periodic). Of course in this case we don’t have 􏰅me-domain samples, but we can s􏰅ll use the FFT to carry out the transform. The complex aperture func􏰅on will be represented by an array of N discrete com- plex values along the aperture, encoding the real and imaginary parts of A(x). Each complex value represents the aperture’s transmi􏰑ance over a small length Δ of the aperture, so that NΔ is the total extent of the aperture. N−􏰆 􏰂 hme􏰉πimj/N (􏰆􏰌) fj= j (􏰆􏰊) m=􏰇 NΔ You can think of frequencies (j/N) × (􏰆/Δ), running from j = 􏰇 to (N − 􏰆), with 􏰆􏰐 Choose appropriate values for N and Δ to make sure you can represent the whole aperture of maximum extent L well enough. Bear in mind that Fast Fourier Trans- form calcula􏰅ons are fastest when the transform length is a power of 􏰉, and that you want Δ to be small enough to resolve the features of the aperture. (Computers are fast these days though; so you can use small values of Δ and correspondingly large values of N. In prac􏰅ce, for such a small problem, the use of N as a power of 􏰉 is not necessary, but it is important if performance is cri􏰅cal.) For the slit problem you can use the func􏰅on to set up an array of the appropriate size filled with zeros and then set the loca􏰅ons where the slit is transparent by assigning non-zero values to “slices” e.g. . You now need a rou􏰅ne to calculate the fast Fourier transform (FFT). You can use the func􏰅on, which is straigh􏰘orward to use (see the code ex- amples from the lectures). It accepts a real or a complex input and produces a complex output. You can call the FFT rou􏰅ne, write out the result to a text file as a and then read it into as separate program which uses for plo􏰍ng. You can do plo􏰍ng in the same program if you prefer. Compu􏰅ng and plo􏰍ng in the same program is not recommended if the computa􏰅on 􏰅me is long (more than a few seconds), but this should not be the case here. You will need to compute the intensity of the pa􏰑ern. You might also want to plot the aperture func􏰅on to make sure you have calculated it correctly. Now think carefully about the coordinates associated with your calculated pa􏰑ern. The discussion at the beginning of this sec􏰅on reminds you about how the fre- quencies appear in the FFT’ed data. Can you understand the form of the intensity pa􏰑ern you have derived? To plot the intensity on the screen as a func􏰅on of actual distance y, you need to work out how to convert the pixels in the Fourier transform into distances on the screen y. To do this you first need to compare carefully Equa􏰅on 􏰆􏰉 and Equa􏰅on 􏰆􏰌 (also referring to Equa􏰅on 􏰆􏰋) which should tell you how to derive y at each pixel value. In addi􏰅on, by interpre􏰅ng the second half of the transform as nega􏰅ve frequencies (or y values in this case) you should be able to plot the intensity pa􏰑ern as a func􏰅on of y for posi􏰅ve and nega􏰅ve y, and plot over this the matching sinc func􏰅on for a slit. If you are having difficul􏰅es with this step it may help to revise your notes from the lectures concerning the loca􏰅on of nega􏰅ve frequencies in the output of an FFT. 􏰆􏰏