Professional Documents
Culture Documents
Download details:
IP Address: 190.27.239.34
This content was downloaded on 07/01/2015 at 19:44
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system
or transmitted in any form or by any means, electronic, mechanical, photocopying, recording
or otherwise, without the prior permission of the publisher, or as expressly permitted by law or
under terms agreed with the appropriate rights organization. Multiple copying is permitted in
accordance with the terms of licences issued by the Copyright Licensing Agency, the Copyright
Clearance Centre and other reproduction rights organisations.
DOI 10.1088/978-1-627-05419-5
Version: 20141001
Preface ix
Acknowledgements x
Author biography xi
vii
Modelling Physics with Microsoft Excel®
10 Electrostatics 10-1
10.1 Coulomb’s law 10-1
10.2 Electrostatic potential 10-3
10.3 Discrete form of Laplace equation 10-4
References 10-6
viii
Preface
The purpose of this work is to show some of the ways in which Microsoft Excel may
be used to solve numerical problems in the field of physics. But why use Excel in the
first place? Certainly Excel is never going to out-perform the wonderful symbolic
algebra tools that we have today—Mathematica. Mathcad1, Maple, MATLAB, etc.
However, from a pedagogical stance Excel has the advantage of not being a ‘black
box’ approach to problem solving. The user must do a lot more work than just
call up a function. The intermediate steps in a calculation are displayed on the
worksheet—of course this is not true with the Solver add-in which is a wonderful
‘black box’. Another advantage is the somewhat less steep learning curve. A high
school student can quickly lean how to get Excel to do useful calculations.
It is assumed that the reader has some prior knowledge of Excel, at least at the
level of what one would find, for example, in Excel for Dummies. The author has
observed while teaching Excel that, while a user might have a good knowledge of the
features of the program, many are at a loss when asked to put them to use. It is only
by hands-on experimentation that one learns the art of constructing an efficient
worksheet. It is hoped that the examples herein will aid the reader to develop his/her
own worksheets.
Some Visual Basic for Applications (VBA) has been introduced with very little
explanation. The purpose here is to show how the power of Excel can be greatly
extended and hopefully to whet the appetite of a few readers to get familiar with the
power of VBA. Those with programming experience in any other language should
be able to follow the code.
The author will be more than happy to reply to email enquiries, be they about a
topic in the book or some other Excel question. Please use the word Excel in the
subject line of each message.
Have fun learning to Excel!
Bernard V Liengme
bliengme@stfx.ca
The workbooks for this project were made using Excel 2013 but they should all
work with the earlier Excel 2007 or Excel 2010 versions. It is assumed that the
reader will have both the text and the Excel file open at the same time.
1
The author wonders how many readers have experimented with SMath Suite, a freely available application
with many of the features of Mathcad. The interested reader might wish to look at http://smath.info/wiki/
(S(c4euu555aw3zio55yas5cj2j))/GetFile.aspx?File=Tutorials/SMathPrimer.pdf.
ix
Acknowledgements
The author thanks fellow Microsoft Excel MVPs Jon Peltier, Bob Umlas and
Jan Karel Pieterse for their help over the years.
x
Author biography
Bernard V Liengme
Bernard V Liengme attended Imperial College London for his
undergraduate and postgraduate degrees; he held post-doctoral
fellowships at Carnegie-Mellon University and the University
of British Columbia. He has conducted extensive research in
surface chemistry and the Mossbauer effect. He has been at
St Francis Xavier University in Canada since 1968 as a Professor,
Associate Dean and Registrar, as well as teaching chemistry and computer science.
He currently lectures part-time on business information systems. Bernard is also
the author of other successful books: COBOL by Command (1996), A Guide to
Microsoft Excel for Scientists and Engineers (now in its 4th edition) and A Guide
to Microsoft Excel for Business and Management (now in its 2nd edition).
xi
IOP Concise Physics
Chapter 1
Projectile trajectory
As this is the first topic in the book, the reader will be given extra details on making
the worksheet to remind him/her of some basic Excel features.
Our aim is to show graphically if a ball kicked with a specified velocity and angle
will by-pass the defenders (located 4 m from the kicker) and make it over the crossbar,
which is at a specified kick-to-goal distance. All three values are controlled by the user.
Having entered the values in B3:D6 of figure 1.1, we select the range B3:C6 and,
using Formulas | Define Names | Create from Selection, give the cells in C3:C6 the
names in B3:B6. With the command Developer | Controls | Insert we add three Spin
Buttons (Form Controls). By right clicking each in turn and opening the Format
Control dialog, we limit the range of each control and assign it to a cell. Thus the first
control is assigned to C3 (velocity) and is limited to the range of values from 5 to 30.
The second control (use copy and paste to make it) is assigned to C4 (angle) with
limits of 20–60 while the third is assigned to C7 (distance) with limits 20–50. In all
three cases, the Incremental and Page change values are set to 1, see figure 1.2.
Enter the text shown in A8:D11 (figure 1.1); formulas will be added later.
Next we generate the data needed to make the graph and solve the problem. See
figure 1.3 for the text needed. The x-dist values are entered with the user’s choice of
methods for entering a linear series in P4:P64 to give values 0, 1, 2, …, 60.
Begin by entering the data in T3:U13; the purpose of these data is explained later.
1-2
Modelling Physics with Microsoft Excel®
=IF(velocity*SIN(RADIANS(angle))*R4-g*R4^2/2>=0,
velocity*SIN(RADIANS(angle))*R4-*R4^2/2, NA())
=IF(AND($Q$8>$U$5,velocity*SIN(RADIANS(angle))*R9-g*R9^2/
2>0), velocity*SIN(RADIANS(angle)) * R9-g*R9^2/2, NA()).
Make a chart using P3:Q64. Then using either Copy & Paste Special, or by right
clicking the chart to bring up the Select Data dialog, add three data series using
T6:U5, T8:U9 and T12:U13 to make bars representing the defenders, the height of
the crossbar and the height of the upright (these extend 30 ft or 12.2 m above the
crossbar); format each to display a line with no markers.
Return to A8:D11 (figure 1.1); the cells A9, B9 and B11 contain the numbers
shown. The others contain the formulas shown in table 1.1.
1-3
Modelling Physics with Microsoft Excel®
Cell Formula
A11 =distance
C9 =VLOOKUP(A9,P4:Q64,2,FALSE)
D9 =IF(C9>B9,“clear”,“intercept”)
C11 =VLOOKUP(A11,P6:Q66,2,FALSE)
D11 =IF(AND( C9>B9,C11>B11),“goal”,“no goal”)
Conditional formats using formulas and fills are used in two cells:
D9: =$C$9<$B$9 red fill and =$C$9>$B$9 green fill
D11: =AND(C9> B9,$C$11>$B$11) green fill.
The worksheet is complete and we are ready to play ball! Experiment with dif-
ferent settings for the three variables velocity, angle and distance.
The cells B3:B7 (figure 1.4) are given the names in the cells to their right. The data
to generate the plot are in P1:AA200, figure 1.5.
1-4
Modelling Physics with Microsoft Excel®
1-5
Modelling Physics with Microsoft Excel®
The formulas are shown in table 1.2. The formulas in row 5 of the worksheet are
copied down to row 200. Note that we need a column of values for the velocity, v, in
the With Drag data. To prevent plotting negative y values, in T5 and AA5 we have
used the simple technique of checking if the preceding value is negative; this may
result in one negative data point but this can be eliminated by setting the y-axis
minimum in the chart to 0.
An extreme example is shown in figure 1.6 with vinit = 60 m s−1, θinit = 45º and
b = 0.05 m s−2. This demonstrates why a golf ball may appear to ‘fall from the sky’.
1-6
IOP Concise Physics
Chapter 2
The pursuit problem
While this is hardly a physics problem, it will demonstrate the use of a numerical
approximation to tackle a difficult calculus problem.
The pursuit problem deals with a predator following its prey; for example, a dog
chasing a cat, a fox after a hare, or a missile targeting a plane. The original pursuit
problem was posed by French mathematician and hydrographer Pierre Bouger in
1732; it was published in the French Academy’s Mémoires de l’Académie Royale des
Sciences and deals with a pirate ship pursuing a merchant vessel. The pirate ship is
travelling in an easterly directly and comes across the merchant ship at a distance
L travelling north. The pirate ship starts at (0, 0) and the merchant at (L, 0) at time
t = 0. The pirate travels at constant speed Vp along a curved path, such that its
velocity vector is always pointing directly at the merchant vessel which has a speed
of Vm with Vp > Vm. This is what is defined as a pure pursuit. The original problem
was to determine the equation that describes the pirate’s path.
⎛ Ym − Yp ⎞
its angle (θ ) relative to the West–East line is given by θ = atan ⎜ L − X ⎟. Whenever
⎝ p ⎠
Vp
the merchant moves a distance ΔYm the pirate moves V ΔYm and the components of
m
Vp Vp
this motion are ΔXp = Vm
ΔYm cos(θ ) and ΔYp = Vm
ΔYm sin(θ ).
(Worksheet: Sheet1 in PursuitProblem.xlsx.) Figure 2.1 shows the first part of our
worksheet. We discuss the range A7:B13 later.
Our ΔYm value (step) is set to 0.005 in cell B3. The distance L (apart) is entered as
10 in B4 while B5 computes the ratio of the speeds of the two vessels with Vp = 10
and Vm = 3. These values are chosen so that we may compare our result with the
calculus approach—see below. Cells B3:B5 are named using the text to their left.
The required formulas are listed in table 2.1.
The formulas in row 4 are copied down to row 703, giving a final Ym value of 3.5.
When we make a plot we find things go awry when the pirate overtakes the
Cell Formula
D3 =apart
G3 the value 0
E3 the value 0
H3 the value 0
D4 =apart
G4 =G3+ratio*step*COS(I4)
E4 =E3+step
H4 =H3+ratio*step*SIN(I4)
I4 =ATAN((E4-H3)/(D3-G3))
2-2
Modelling Physics with Microsoft Excel®
1 ⎡ (1 − x / x0)n (1 − x / x0)−n ⎤ n
y (x ) = ( x0 − x ) ⎢ − ⎥+ x0
2 ⎣ 1+n 1−n ⎦ 1 − n2
where x0 is our L or apart value, and n is Vm/Vp which means that n = 1/ratio.
This equation is used in Sheet2 to generate the data that are incorporated in the
chart shown on the right of figure 2.2. The numerical method clearly produces quite
good results.
To find the point of intersection as predicted analytically we let x = x0 in the above
n
equation; this makes the first term equal to zero leaving y (L ) = x0 which is
1 − n2
3.297. This is computed in B13 of Sheet1 with =n/(1-n^2)*apart where n is the
inverse of our ratio of speeds.
From the chart we can see that the numerical method gives the intersection at
about y = 3.3. A more precise value is obtained in B8 with the formula =VLOOKUP
(apart,$G$3:$H$703,2), which returns 3.293. This is in excellent agreement
with the analytical answer, a mere 0.1% difference. However, it should be noted that
with a step size of 0.01, the intersection point is found at 3.278 (0.6% error). When
using a numerical modeling method one should experiment with decreasing step
sizes until one reaches a point when the answer remains unchanged for all intents
and purposes.
2-3
Modelling Physics with Microsoft Excel®
One may also make the point that a numerical approach which supports the
result of a complex analytical process can give one faith in the correctness of the
analytical result.
References
[1] Severdia M 2008 Pursuit curves http://online.redwoods.edu/instruct/darnold/DEProj/sp08/
mseverdia/pursuit.pdf
[2] Nagle R K 2012 Fundamental of Differential Equations and Boundary Problems 6th edn
(Boston, MA: Addison-Wesley) p 145
[3] Lloyd M 2006–07 Pursuit curves http://www.hsu.edu/uploadedFiles/Faculty/Academic_
Forum/2006-7/2006-7AFPursuit.pdf
2-4
IOP Concise Physics
Chapter 3
Equation solving with and without Solver
In this topic we will explore the use of Solver1. At the same time we will look at other
ways of solving equations to give the reader further insight into using Excel.
3.1 The van der Waals equation: the fixed point iteration method
Suppose we have f (x) = 0 and that it is possible to recast this to x = g(x), then with
some initial guess for x 0 we may use the iteration x n+1 = g(xn) until successive values
are the same to some required precision.
Our task is to find the molar volume of ammonia gas at a given pressure and
temperature using the van der Waals equation
⎛ a ⎞ ⎛ a ⎞
⎜ P + 2 ⎟ ( Vm − b) = RT or Vm = RT ⎜ P + 2 ⎟ + b.
⎝ Vm ⎠ ⎝ Vm ⎠
The second form suggests we try the method of fixed point iteration. We enter a
value for V in the right side of the alternative form to compute a new V value; we use
this second value to compute a third; we continue to do this until two successive
values are the same to within the required tolerance.
(Worksheet: Sheet1 in EqnSolving.xlsm.) In figure 3.1, the range B7:B11 contains
the values of the various data items needed for the problem; each value has been
named with the letter to its left2. In B15:B23 we have the results of the successive
approximation method.
1
If you need to install Solver (i.e. the Analysis group in the Data tab does not show Solver) see http://office.
microsoft.com/en-us/excel-help/load-the-solver-add-in-HA102749006.aspx.
2
Excel does not permit names that can be mistaken for cell references, nor does it allow the letters C and R. If
one selects E3:F7 and uses Formula | Defined Names | Created from Selection then F7 gets the name R_ with an
underscore as the last symbol.
It is convenient, but not essential, to start in B15 with a volume computed from
the ideal gas law (the formula is = R_*T/P). In row 2 we have: A16 = A15 + 1;
B16 = R_*T/(P + a/B15^2) + b. We can select A16:B16 and drag the fill handle
down until two successive results are as close as we require. Column C is to show the
user how quickly the method is converging.
3-2
Modelling Physics with Microsoft Excel®
3-3
Modelling Physics with Microsoft Excel®
One condition is =ABS(B17-B18) >0.0000001 -> red fill; the other is =ABS
(B17-B18) <=0.0000001 -> green fill.
IMPORTANT: a reader with previous experience of Solver might wonder why
we have used a constraint when we could have constructed a cell to compute the
value of the expression
⎛ a ⎞
⎜ P + 2 ⎟ (Vm − b) − RT
⎝ Vm ⎠
and used the top part of the Solver dialog as shown in figure 3.5 where C17 holds the
Excel formula for the above expression.
From experience, and on the advice of FrontLine Systems Inc. (who license
Solver to Microsoft and other spreadsheet vendors), the author has found that using
the constraint method can give better results and is more flexible, as we shall see in
later demonstrations.
IMPORTANT: while Solver is generally very good at finding a solution, the
user may encounter situations were it fails unless the starting value is ‘in the same
3-4
Modelling Physics with Microsoft Excel®
ball park’ (not a very technical term!) as the solution. The reader might wish to
experiment with the value 0.5 in B16 and see how Solver handles this starting value.
To get help on the Excel Solver add-in visit the site http://www.solver.com/excel-
solver-help.
(Worksheet: Sheet2 in EqnSolving.xlsm.) The van der Waals equation can also be
written in virial form. The reader may wish to experiment with the worksheet. There
is nothing new about the methodology so no discussion is needed.
3-5
Modelling Physics with Microsoft Excel®
3
The author wishes to thank Jon Peltier for permission to use (with modification) some VBA from his website
http://peltiertech.com/Excel/WordPress/link-excel-chart-axis-scale-to-values-in-cells. This code is in Module 1
of the workbook EqnSolving.xlsm.
3-6
Modelling Physics with Microsoft Excel®
coefficients, we know that the real roots will lie on the interval (−4, 4). Figure 3.6
shows part of a table of (x, y) pairs for f (x) over the interval (−4, 4) and the resulting
XY chart. It is clear that this chart is totally useless as far as estimating the roots of
f (x). Clearly we need to plot a different range. Alternatively, we could alter the
bounds of the two axes in order to display just that part of the curve that is of
interest. We could do this by formatting the two axes one at a time. But here is a
more convenient way. The two buttons on the worksheet are each assigned to a VBA
subroutine: one to customize the chart and the other to reset it in case things go
wrong. Enter values into the range E6:E13 and click the Customize button. Some
experimentation reveals that 3, −2, 1, 25, −10 and 5 are a good start while 2.5, −1.5,
0.25, 3, −8 and 1 are even better. The lower chart in the figure is a screen capture4 of
a chart with these setting. We can see the roots are −1, 1 and 2.
We will not discuss the VBA code except to note, for the interested reader,
why named ranges have been used. Suppose someone restructures the worksheet
(maybe adds/deletes some columns/rows) then code such as .MaximumScale =
ActiveSheet.Range("$E$6").Value would now point at the wrong cell.
NOTE: if you experiment with this worksheet and make a new chart you should
be aware that the VBA code expects the chart to be named ‘Chart 1’. If you activate
a chart and in the Name Box (to the right of the Formula Bar) type Chart 1 and tap
the Enter key, then your new chart will have the correct name.
The reader may wish to perform the following experiment:
a) Click on the Sheet4 tab and holding down the CTRL key drag the tab to the
right. This produces a new sheet called Sheet4(2) when the CTRL key is released.
b) Edit B2’s formula in the new sheet from = A4^6 -4*A4^5 + 4*A4^4 - A4^2
+4*A4 -4 to = A4^6 -4.125*A4^5 + 3.75*A4^4 - A4^2 + 4*A4 -5
c) Customize the chart to estimate the new roots.
4
One can make a static picture of a chart by activating it (i.e. clicking anywhere on the chart) and using the
command Home | Clipboard | Copy as Picture followed by Paste.
3-7
Modelling Physics with Microsoft Excel®
These are copied to row 5. The new estimate (x1) is found in B5 with
= B4-C4/D4. The range A5:D5 is selected and the fill handle pulled down until
we get an f (x) value of zero (or close to zero). Our roots are found to be −1.029
61 and 2.790 99.
Note that the right side fails to get f (x) to be exactly zero. To fully understand
this, one needs to appreciate that Excel, like most mathematical computer appli-
cations, stores decimal values in binary format using the IEEE 754 convention. Since
there are a fixed number of bits, one gets ‘round-off ’ errors. So we should treat
anything less than 1 × 10−15 as zero.
Some useful sites for learning about IEEE 754 are:
a) http://www.cpearson.com/excel/rounding.htm
b) http://support.microsoft.com/kb/78113/en-us
c) http://docs.sun.com/source/806-3568/ncg_goldberg.html
d) http://blogs.office.com/2008/04/10/understanding-floating-point-precision-
aka-why-does-excel-give-me-seemingly-wrong-answers/
3-8
Modelling Physics with Microsoft Excel®
run we get the results shown in D5:E6 (these were merely copied from A4:B5 after
running Solver). When Solver was run a second time the results in D8:E10 were
obtained but no further change was noted when Solver was run a third time. The
moral is: always run Solver at least twice to see if it improves its result!
It is noteworthy that with a starting value of −1.5, Newton’s method quickly
converged to give a value of x that made f (x) exactly zero while Solver manages
‘only’ 1 × 10−10. However, this degree of precision is generally sufficient for most
purposes.
3-9
Modelling Physics with Microsoft Excel®
3-10
Modelling Physics with Microsoft Excel®
Tools | What-If Analysis | Goal Seek, and complete as shown in the right side of
figure 3.10 and click the OK button. Goal Seek finds that a value for x of 1.134 712
makes f (x) equal to −0.0012. This may be close enough to zero for some purposes
but it can be improved. The trouble is that the default setting for Goal Seek is
a precision of a mere 0.001. Use the command File | Options | Formulas, locate
the Maximum Change box it the top right area and enter 0.000 0001. Click OK to
return to the worksheet and re-run Goal Seek. This time we get x = 1.134 724 and
f (x) = −9 × 10−9. Note that Goal Seek does not retain the model the user last set up
but that the precision setting in the Maximum Change now apples to all further Excel
workbooks. This is the reverse of Solver’s behavior.
Neither form of the recurrence formula is well suited for translation into an
Excel formula but the second form is readily coded in VBA. The two user-defined
functions5 are:
5
The code is in Module 2 of the workbook EqnSolving.xlsm.
3-11
Modelling Physics with Microsoft Excel®
3-12
Modelling Physics with Microsoft Excel®
shape causes a VBA subroutine6 to run and this fills both the starting values of x and
the final results. The subroutine has been run prior to making the screen capture.
6
The code is in Module 3 of the workbook EqnSolving.xlsm.
7
Select F17:H19, type the formula and commit it using CTRL + SHIFT + ENTER. Excel will place the
formula in curly brackets { }.
3-13
Modelling Physics with Microsoft Excel®
Figure 3.14 shows another part of the same worksheet where the problem is set up
to solve with Solver.
8
David R Levin http://tx.technion.ac.il/~dlewin/054374/Day_5.pdf.
3-14
Modelling Physics with Microsoft Excel®
been named9 x1_ and x2_. They have been given the initial values of 1 in the hope
that these starting values will allow Solver to perform its task. In the green area we
have the two functions; these use the formulas =4-(x1_-3)^2 + 0.25*x1_*x2_
-(x2_-3)^2 and = 5-(x1_-2)^2-(x2_-2)^3, respectively. The target values
are in the pink area.
Solver (see figure 3.16) is set up with nothing in the Set Objective box, the By
Changing Cells are x1_ and x2_, and the constraint requires Solver to make fx1 and
fx2 equal to their respective target values. Carefully note that we had to uncheck the
Make Unconstrained Variables Non-negative since we may very well get negative x1
and x2 values—it is a little annoying that the Solver’s default is to have the box
checked, since one could readily forget to uncheck it!
Running Solver once with the constraint precision left at the default value of
0.000 001 gave the function cells the values −4.8064 × 10−7 and −2.2031 × 10−7.
Running it a second time resulted in values of 2.0385 × 10−12 and 8.7961 × 10−12;
these we will accept as being close enough to zero. The values found by Solver for
the variables are x1 = 0.883 825 485 593 73 and x2 = 3.554 189 768 020 48. The
internet document reported values of 0.8838 and 3.5542, so the two methods agree at
least to four decimal places.
9
Recall that since X1 is a valid cell reference, Excel will use the name x1_ (with the underscore) when we ask it
to use the text in the row above to name the cells.
3-15
Modelling Physics with Microsoft Excel®
The default setting is 0.0001 but decreasing this to 0.000 000 01 often improves the
result. However, for a very complex problem, this may result in lengthy computation
times when the extra precision is not required.
3-16
IOP Concise Physics
Chapter 4
Temperature profile
Consider a thin metal sheet (figure 4.1) whose edges are maintained at specified
temperatures. The sheet is allowed to come to thermal equilibrium. Our task is to
compute the approximate temperatures at various positions on the plate. This we
shall do in three different ways: formulas with circular references, matrix math and
with Solver.
We need to make some assumptions. The first is that the two faces of the plate are
thermally insulated. Thus there is no heat transfer perpendicular to the plate. The
second assumption starts with the mean-value theory, which states: if P is a point on
a plate at thermal equilibrium and C is a circle centered on P and completely on the
plate, then the temperature at P is the average value of the temperature on the circle.
The calculations required to use this theory are formidable, so we will use an
4-2
Modelling Physics with Microsoft Excel®
These equation may be written in a more general form using variables a, b, c and d
rather than numerical values. It may then be rearranged in the form:
t1 = ( t2 + t3 )/4 + (a + d )/4
t2 = ( t 4 + t1)/4 + (a + b)/4
t3 = ( t1 + t 4 )/4 + (c + d )/4
t4 = ( t2 + t3 )/4 + (b + c )/4.
4-3
Modelling Physics with Microsoft Excel®
To be able to use a matrix method, each equation must have the same form:
t1 = ( 0.00t1 + 0.25t2 + 0.25t3 + 0.00t 4 ) + (a + d )/4
t2 = ( 0.25t1 + 0.00t2 + 0.00t3 + 0.25t 4 ) + (a + b)/4
t3 = ( 0.25t1 + 0.00t2 + 0.00t3 + 0.25t 4 ) + (c + d )/4
t 4 = ( 0.00t1 + 0.25t2 + 0.25t3 + 0.00t 4 ) + (b + c )/4.
4-4
Modelling Physics with Microsoft Excel®
1
From FrontLine Systems Inc who license the default Solver add-in to Microsoft and other vendors of
spreadsheet applications. See www.Solver.com.
4-5
Modelling Physics with Microsoft Excel®
4-6
Modelling Physics with Microsoft Excel®
want the Variables cells to take on values such that C5 is equal to C13, which in
turn is equal to the average of C5’s four nearest neighbors. There is no need to
adjust any of the Solver options and the GRG Nonlinear engine is the right one for
the task. Solver finds the solution displayed in figure 4.9 which agrees with our
earlier methods.
4-7
IOP Concise Physics
Chapter 5
Numerical integration
This topic demonstrates four numerical methods for evaluating definite integrals: the
trapezoid rule, Simpson’s ⅓ rule and two slightly different Monte Carlo methods. It
is convenient, from a pedagogical stance, to solve a definite integral for which an
analytical solution may be found.
π /2 1
The example used is ∫ sin(2x )exp(1 − cos(2x ))dx for which 2 exp(2sin2(x ))∣0π /2 =
0
3.194 528 049 465 33 is the analytical result [1].
Each of the methods described here rely on the concept that if the definite
b
integral ∫ f (x )dx = I then I is the area of the function under the curve f (x) for a ⩽
a
x ⩽ b.
The Simpson’s ⅓ rule uses strips made for three data points through which a
parabola is fitted. This method has two limitations: the data must have equal Δx
values and there must be an odd number of data points. For this rule we have
n−2
1
I≈ ∑ (y + 4yi + 1 + yi + 2 )Δx .
3 i
i = 1,3,5
D4 = SUM(D9:D58) E4 = E4-Analytical
D5 = D4-Analytical E5 = (E4-Analytical)/Analytical
D6 = (D4-Analytical)/Analytical E6 = SUM(E9:E58)
Figure 5.1 shows an Excel implementation of the two rules. As expected Simp-
son’s rule gives a more accurate result. The close agreement between the Simpson
rule result and the analytical result (differing by 1 in the sixth decimal place) is
fortuitous and comes about because our function is very smooth. Usually one
repeats the exercise with ever decreasing step sizes until the areas cease to change
within the required precision.
(Worksheet: Sheet1 in Integrate.xlsm.) Let us see how this was implemented. In
column A (heading x) we compute a series 0 to π/2 in steps of π/100; A9 has value 0
while A10 has the formula =A9+0.1*PI() and this is copied down to row 59.
Column B (heading f (x)) computes the values of the function for each x value: the
formula in B9 is =SIN(2*A9)* EXP(1-COS(2*A9)) and this is filled down to
B59. The data in A8:B59 were used to construct the chart.
The formula in D9 is =(1/2)*(B10+B9)*(A10-A9) and this is filled down to
D58 (not D59). Note we have 51 data points so we have 50 stripes for the trapezoid
approximation.
In E9 the formula is =(1/3)*(A10-A9)*(B9+4*B10+B11)); cells E9 and
E10 (a blank cell) are dragged down to E58. Our 51 data points make 25 stripes for
the Simpson’s approximation.
The formulas in E4:F6 are shown in table 5.1.
There is a cell named Analytical which holds the analytical result of 3.194 528 049
465 33. All calculated values have been formatted to display six decimal places but
Excel’s full precision is used throughout.
5-2
Modelling Physics with Microsoft Excel®
1
We have only 11 points to use in the compact form, so the likelihood of a typo error is slight. Using it in the
previous example with 50 points might be foolhardy.
5-3
Modelling Physics with Microsoft Excel®
coordinates as (5.71, 37.55) which are satisfactorily close to our Simpson’s approx-
imation values.
5.3 Monte Carlo method I
It is traditional to explain the classical Monte Carlo integration method as follows:
consider a 1 meter square board with an inscribed circle of diameter 1 meter. Darts are
thrown randomly at the board; a count is made of how many were thrown and how many
fell within the circle. Then we make the assumption (assuming totally random throwing)
Hits within circle Area of circle π 0.52
≈ = 2 .
Total hits Area of square 1
This gives a method to approximate π; the implementation is generally performed
with a quarter circle.
(Worksheet: Sheet3 in Intergration.xlsm.) Imagine a rectangle with corners at (0,0),
(π/2,0), (π/2,4) and (0,4) drawn on the chart in figure 5.1—a chart on Sheet3 shows such
a rectangle. Solver tells us that, for 0 ⩽ x ⩽ π/2, the function has a maximum value of
3.9647 at x = 0.712 071 so the value of y = 4 for the top line of the rectangle is fine. We
will simulate the dart throwing experiment by generating random x and y values in the
range 0–π/2 and 0–4, respectively; we will test if each point represented by these two
values falls under the curve.
In figure 5.3 (concentrate for now on columns A through D) we have the formula
=RAND()*PI()/2 in B9 and = RAND() * 4 in C9. The formula = –(C9< = SIN(2
* B9)*EXP(1-COS(2*B9))) in D9 tests the position of this (x, y) point. Without
the double negation this formula would return either FALSE or TRUE; the double
negation converts these results to 0 and 1 allowing us to sum the number of hits
below the curve. The range B9:D9 is dragged down to row 2008 giving us 2000 data
points. The formula =(4*PI()/2)*SUM(D9:D2008)/COUNT(D9:D2008) in
D5 gives the approximation for the area under the curve. Pressing F9 causes the
worksheet to be recalculated and a new approximation is found.
A user-defined VBA function (MonteArea) is used to generate five approxima-
tions (in G7:G10). These are averaged in H7. The results shown are for n = 10 000
(i.e. throwing 10 000 darts); the value in F6 may be changed to another value—a
value of 100 000 will improve the approximation and will not tie up a modern
computer for more than a fraction of a second. The chart graphically demonstrates
the results by plotting the five area values together with a line for the average and
another for the analytical result. Your author disobeyed the golden rule that column
2
For quickness we can ask [1] to find INT −0.5x3 + 4x2 + 10x from 0 to 10, INT −0.5x4 + 4x3 + 10x2 from
0 to 10, and INT (−0.5x3 + 4x2 + 10x)2 from 0 to 10.
5-4
Modelling Physics with Microsoft Excel®
charts always have zero as the minimum for the y-axis, but he abstained from hitting
F9 until a near-perfect value was obtained.
The code for MonteArea is shown below. It generates random x and y values as
in the worksheet method. Then the resulting position is tested to see if it lies under the
curve. The curve tested is defined in the user-defined function (UDF) myfun; this makes
it easier to alter the procedure for different curves. The UDF MonteArea is called in
G6 with the formula =MonteArea(F6) and this formula is dragged down to G10.
Function MonteArea(n) Function myfun(x)
Application.Volatile Pi = 4 * Atn(1)
Pi = 4 * Atn(1) myfun = Sin(2 * x * Pi / 2) * _
Randomize Exp(1 - Cos(2 * x * Pi / 2))
mycount = 0 End Function
For k = 1 To n
x = Rnd
y = Rnd * 4
If y < = myfun(x) Then mycount = mycount + 1
Next k
MonteArea = (mycount / n) * (4 * Pi / 2)
End Function
5-5
Modelling Physics with Microsoft Excel®
Function MonteArea2(n)
Application.Volatile
Pi = 4 * Atn(1)
5-6
Modelling Physics with Microsoft Excel®
Randomize
For k = 1 To n
x = Rnd
y = myfun(x)
mysum = mysum + y
Next k
myaverage = mysum / n
MonteArea2 = myaverage * (Pi / 2)
End Function
π
∫0 1
2
sin(θ )dθ
1 2
prob = 1
= = = 0.6366197
×π π /2 π
2
5-7
Modelling Physics with Microsoft Excel®
We will turn the problem around and use a Monte Carlo method to estimate the
probability and hence get an estimate for π from the expression π = 2/prob.
(Worksheet: Sheet1 in Buffon.xlsm.) Figure 5.7 shows a worksheet set up for this
problem using a VBA user-defined function.
5-8
Modelling Physics with Microsoft Excel®
Function buffA(n)
Application.Volatile ‘this enables us to press F9 to generate
new data
Randomize
For j = 1 To n
d = Rnd / 2
theta = Application.Radians(Rnd * 180)
If d < = 0.5 * Sin(theta) Then
hits = hits + 1
End If
Next j
buffA = hits / n
End Function
Since we have one million calculations every time the worksheet calculates, it is
advisable to set the Calculation option to manual3 while using this file, as the
recalculation takes a minute or two on a modest PC. Remember to set it back to
automatic when done.
References
[1] http://wolframalpha.com
[2] Buffon G 1777 Essai d’arithmétique morale Hist. Nat. Gén. Particulière Supp. 4 46–123
3
The calculation method may be set by either of two methods. The first method is to open the File tab, located
the Options tab and within the Options dialog locate and open the Formula tab where the first group is labeled
Calculations options. The alternative method, and more directed route, is Formulas | Calculation | Calculation
Options.
5-9
IOP Concise Physics
Chapter 6
Approximate solutions to differential equations
sets are shown in the worksheet, giving us approximations with h values of 0.2, 0.05,
0.025 and 0.01. The data sets are charted in the left panel of figure 6.2 where it is seen
that the values converge as h decreases. Happily they converge on the exact solution.
This is not a particularly well-conditioned function and we see that a very small
step value (h) is needed to get a good approximation. Of course, in reality we could
not have access to the exact solution, but we can see that as h gets smaller the
solutions converge. So we would keep decreasing the step size until two results are
within the required precision.
(Worksheet: Euler2 in DiffEquations.xlsm.) Many problems can be solved by
Euler’s method without resorting to such small step sizes. Euler2 is set up similarly to
Euler1 but with just three data sets. Here we solve y′ = 4 exp(0.8x ) − 0.5y
with y (0) = 2 . The convergence is somewhat faster than in our first example, as
seen in the right panel of figure 6.2. Note that Euler2 can be rapidly modified for
6-2
Modelling Physics with Microsoft Excel®
other problems. One needs to: (i) change the text in row 4; (ii) adapt the formula in
D8 for the new problem and drag this down the column; (iii) copy D8 to I8 and N8
and copy both down their columns; and (iv) adapt the formulas in column O for the
exact solution if known.
(Worksheet: Euler1 in DiffEquations.xlsm.) Returning to the first problem on
Sheet1, we will see how a simple VBA UDF may be used to experiment with even
small values of h without taking up thousands of cells. Figure 6.3 shows a table of
results (the errors reported on row 17 are for n = 200 000) together with a chart (note
the logarithmic x-axis) that demonstrates the convergence.
It is left to the interested reader to open the Visual Basic Editor to view the code.
Please note the use of an array to hold the two values (y(1) and y(2)) computed by
the UDF. This requires that we selected two cells under the y(1) and y(2) headings,
type the equation and commit it with CTRL+SHIFT+ENTER as it is an array
formula—it returns more than one value.
6-3
Modelling Physics with Microsoft Excel®
Euler’s method has the advantage of being very simple (compared to the Runge–
Kutta method discussed below). It is often criticized for requiring small step sizes
and hence requiring a lot of computer operations. The author finds this criticism a
little strange; with a normal Windows computer, the quarter of a million iterations
needed to generate the data above took place in the blink of an eye. Perhaps the
comment is fair if one has a very large model (maybe a computer game or a climate
model) with thousands of ODEs to solve in a short time!
h
yn + 1 = yn + (k1 + 2k2 + 2k3 + k 4 )
6
k1 = f (xn , yn )
⎛ 1 1 ⎞
k2 = f ⎜xn + h , yn + hk1⎟
⎝ 2 2 ⎠
⎛ 1 1 ⎞
k3 = f ⎜xn + h , yn + hk2 ⎟
⎝ 2 2 ⎠
k 4 = f (xn + h , yn + hk3 ) .
For a comparison with the Euler method we will again solve for y(2) given
2y − 18x
y′ = 1 + t and y(0) = 4 and compare our results with the exact solution of
y = − 5x 2 + 8x + 4.
(Worksheet: RungeKutta1 in DiffEquations.xlsm.) We set up a worksheet as
shown in figure 6.4. The cells C5:C7 have been named using the text in B5:B7.
The formulas in B9:H10 are shown in table 6.2.
The range B10:F10 is then dragged down to row 49. The formulas for the four
k values would be rather complex (and error prone) if we tried to use just Excel
formulas. It is much better to use VBA user-defined functions—the interior par-
entheses in the k value formulas are not required but are added to improve
readability. The use of a UDF not only simplifies the equations on the worksheet
but it also facilitates making simple edits to solve other problems. Note how a 40
step process (an h value of 0.05) gives a far superior estimation compared to
1
Note that various textbooks give different but equivalent definitions for the k values.
6-4
Modelling Physics with Microsoft Excel®
Euler’s method. But the expense is more complex formulas. The VBA code used is
as follows:
'Differential equation y'=(2y-18x)/(1+x)
Function DiffEqn(x As Double, y As Double) As Double
DiffEqn = (2 * y - 18 * x) / (1 + x)
End Function
6-5
Modelling Physics with Microsoft Excel®
The cells in B4:B8 are named by the text to their left. The values in A11:D20 are
produced by the VBA subroutine called RKauto the code for which is shown below.
In E11 we have the formula =C11-Exact and this is copied down to E20. Note that
by adjusting the UDF DiffEqn, and perhaps removing reference to the exact solu-
tion, this worksheet can be used for many different ODE problems.
Sub RKauto()
Dim k1 As Double, k2 As Double, k3 As Double, k4 As Double
Dim x As Double, y As Double, myRange As Double, yold As Double
Dim h As Double, j As Integer, n As Integer, m As Integer, MyLine
As Integer
h = Range("InitialH")
myRange = (Range("FinalX") - Range("InitialX"))
MyLine = 11
For j = 1 To 10
yold = y
x = Range("initialX")
y = Range("initialY")
n = myRange / h
6-6
Modelling Physics with Microsoft Excel®
For m = 1 To n
k1 = DiffEqn(x, y)
k2 = DiffEqn(x + h / 2, y + h * k1 / 2)
k3 = DiffEqn(x + h / 2, y + h * k2 / 2)
k4 = DiffEqn(x + h, y + h * k3)
y = y + (h / 6) * (k1 + (2 * k2) + (2 * k3) + k4) ‘compute y
Cells(MyLine, "A") = h
Cells(MyLine, "B") = n
Cells(MyLine, "C") = y
If j > 1 Then Cells(MyLine, "D") = yold - y
MyLine = MyLine + 1
h=h/2 ‘the h value is halved for each iteration of j
Next j
End Sub
1
yn + 1 = yn + (k1 + 2k2 + 2k3 + k 4 )
6
1
u n − 1 = u n + (q1 + 2q2 + 2q3 + q4 )
6
k1 = hg (xn , yn , u n )
q1 = hf (xn , yn , u n )
⎛ 1 1 1 ⎞
k2 = hg ⎜xn + h, yn + k1, u n + q⎟
⎝ 2 2 2 1⎠
⎛ 1 1 1 ⎞
q2 = hf ⎜xn + h, yn + k1, u n + q⎟
⎝ 2 2 2 1⎠
⎛ 1 1 1 ⎞
k3 = hg ⎜xn + h, yn + k2, u n + q ⎟
⎝ 2 2 2 2⎠
⎛ 1 1 1 ⎞
q3 = hf ⎜xn + h, yn + k2, u n + q ⎟
⎝ 2 2 2 2⎠
k 4 = hg (xn + h , yn + k3, u n + q3 )
q4 = hf (xn + h , yn + k3, u n + q3 ) .
6-7
Modelling Physics with Microsoft Excel®
T
y″ = −g y (0) = 0 and y′ (0) = 0.
M − mt
Making the substitution y′ = u (the rocket’s velocity) we get two coupled first-
order ODEs:
y′ = u y (0) = 0
T
u′ = −g u (0) = 0.
M − mt
Function Rocket(t)
Rocket = 10000 / (100 - 5 * t) - 9.8
End Function
6-8
Modelling Physics with Microsoft Excel®
A7 =tinit A8 =A7+
B7 =yinit B8 =B7+(D7+2*F7+2*H7+J7)/6
C7 =uinit C8 =C7+(E7+2*G7+2*I7+K7)/6
D7 =h*C7 D8 =h*C8
E7 =h*Rocket(A7) E8 =h*Rocket(A8)
F7 =h*(C7+E7/2) F8 =h*(C8+E8/2)
G7 =h*Rocket(A7+h/2) G8 =h*Rocket(A8+h/2)
H7 =h*(C7+G7/2) H8 =h*(C8+G8/2)
I7 =h*Rocket(A7+h/2) I8 =h*Rocket(A8+h/2)
J7 =h*(C7+I7) J8 =h*(C8+I8)
K7 =h*Rocket(A7+h) K8 =h*Rocket(A8+h)
Cell Formula
M7 =40000*(1-0.05*A7)*LN(1-0.05*A7)+2000*A7-4.9*A7^2
N7 =-(10000/5)*LN(1-0.05*A7)-9.8*A7
6-9
Modelling Physics with Microsoft Excel®
References
[1] www.wolframalpha.com
[2] Hoffman Joe D 2001 Numerical Methods for Engineers and Scientists 2nd edn (New York:
Marcel Dekker)
2
In [2] Hoffman gives the correct algebraic equations but makes a few arithmetical errors in his equations
(7.321) and (7.322) when substituting the numerical values. Likewise, there is a numeric error in (7.327d) which
causes subsequent values to be incorrect. However, Hoffman’s table 7.16 has the correct values.
6-10
IOP Concise Physics
Chapter 7
Superposition of sine waves and Fourier series
7-2
Modelling Physics with Microsoft Excel®
The sine and cosine functions both have a periodicity of 2π; that is to say sin(x) =
sin(x + 2π) = sin(x +2 nπ) for any integer value of n. If we wish to generate a function
f (x) having a periodicity of 2L we need to use the series1:
∞ ∞
⎛ nπx ⎞ ⎛ nπx ⎞
f (x ) = a 0 + ∑an cos⎜⎝ L ⎟⎠ + ∑bn sin⎜⎝ L ⎠
⎟.
n=1 n=1
(Worksheet: Sheet5 in SineWave.xlsx.) Let us find the Fourier series for a tri-
angular wave form described by f (x ) = 0.6 for 0 ⩽ x ⩽ 10. The period (2L) of such
a function is clearly 10. Substituting 0.6xI for f(x) in the above equations we find2
that a 0 = 3, a n = 0 and bn = −6/nπ. The worksheet is designed to enable us to find the
Fourier series for 2, 3, 4, 5 or 6 harmonics. Figure 7.4 demonstrates how the series
gets closer to f (x) as the number of harmonics increases.
1
Some texts use a 0/2 in place of a 0 but they use a different formula to compute a0.
2
Perhaps with help from Wolframalpha.com!
7-3
Modelling Physics with Microsoft Excel®
x = a sin(θ ) ⎫
⎬ 0 < θ < 2π .
y = b cos(θ )⎭
7-4
Modelling Physics with Microsoft Excel®
being named a and b, respectively. We will limit ourselves to a and b values in the
range 0–10. Starting with a = 10 and b =10, we make an XY chart of a circle (it will
be necessary to select B6:D47 to avoid the θ values being used) and we format each
axis to have bounds of −10 to +10. Then, by eye, we attempt to resize the chart to
make both the chart area and the plot area square. Be aware that when printed the
perspective of the chart may change.
(Worksheet: Sheet7 in SineWave.xlsx.) Lissajous curves are the family of curves
described by the parametric equations
x(t ) = A sin(αt + δ )
y(t ) = B cos(βt ).
Our worksheet is shown in figure 7.6. Cells D3:D7 hold the values of the
parameters while D8 stores the incremental t value. In C11 we have the formula
=A*SIN(alpha*A11+delta) and in D11 =B*SIN(beta*A11)l these are copied
down to row 93.
We begin with A = 8, B = 8, α = 1, β = 1 and δ = PI()/2 and make an XY plot
using C11:D93. This will generate a circle so we fix the bound of the two axes to −8
and 8, and adjust the chart to make the chart area and plot area square by eye. Now
we are ready to experiment with other values but keep the absolute values A and B
to a maximum of 8 since we have locked the axes bounds. Figure 7.7 shows some
results. Note that when δ equals π/2 we get various conic sections.
7-5
Modelling Physics with Microsoft Excel®
7-6
IOP Concise Physics
Chapter 8
Fast Fourier transform
In this topic we set ourselves the task of capturing a noisy sinusoidal signal and
performing a spectral analysis. To simulate the ‘capture’ we will use Excel for-
mulas to generate the data. We will perform the spectral analysis using the built-in
Fourier Analysis1 tool. Figure 8.1 shows a sample input signal and its spectral
analysis plot.
(Worksheet: Sheet1 in FastFourier.xlsx.) Figure 8.2 shows the worksheet where a
signal consisting of two cosine waves is generated and then random noise is added.
Rows 3 and 4 set the parameters for the cosines; note we are using frequencies of
60 and 150 Hz. Rows 6 and 7 specify the sampling procedure and the amount of
noise to be added.
Starting in row 10 we have the formulas to generate the signal. Column A has the
time values with zero in A10 with subsequent values increased by the reciprocal of
1
The author is grateful to Doug Godsoe, PhD, PEng for assistance with this tool.
the sample rate (C6). The formulas in B10:D10, which are copied down to row 73
(giving 64 values) are:
B10: = $C$3*COS(A10*2*$C$4*PI()) + $F$3*COS(A10*2*$F$4*PI())
C10: = $F$6*(RAND()-0.5)
D10:= B10+C10
The worksheet2 also has plots of the signal with and without noise.
(Worksheet: Sheet2 in FastFourier.xlsx.) Figure 8.3 shows the spectral analysis
result. The values for the sample rate and size are taken from Sheet1 with formulas
= Sheet1!C6 and = Sheet1C7. The ‘captured’ signal from Sheet1 is obtained
using = Sheet1!D10 in A6 and copying this down to row 69.
Now we are ready to use the fast Fourier transform (FFT) tool. Using the
command Data | Analysis | Data Analysis we open the dialog listing all the built-in
Excel analysis tools. When Fourier Analysis is double clicked we see and complete its
dialog box, figure 8.4.
It should be noted that the size of the Input Range must be a power of 2; we have
64 data points (i.e. 26 values). When the OK button is clicked we may get a warning
that the data in the output range are about to be overwritten; click the OK button3.
We now have our FFT data. Note the complex numbers.
2
Because we are using the RAND function, the reader should not be surprised if columns C and D differ
from the figure’s value. Indeed the values and the plot of noisy data will change if anything is done to the
worksheet.
3
For some odd reason the cells in the output range will now be selected. Click on any blank cell to avoid any
problem this could cause. The Fourier Analysis tool has another oddity: if you use it on a worksheet and then
open another worksheet (in the same or a different workbook) the settings in the dialog are preserved.
8-2
Modelling Physics with Microsoft Excel®
The f values in column C begin with zero in C6 and the formula = C6+$C$2/$C
$3 in C7; this is copied down to C38. For the Power values we use the formula4
= 2*POWER(IMABS(A6)/$C$3,2) in D6 and copy it down to D39. The spectral
analysis plot is made from C6:D39.
Even with quite noisy data the procedure clearly shows the underlying compo-
nents at 60 and 150 Hz.
4
The 2 in the formula allows for the fact that we have a one-sided PSD function showing only positive
frequencies.
8-3
IOP Concise Physics
Chapter 9
Applying statistics to experimental data
The ‘table’ t-test value is obtained from the Excel T.INV.2T function. Since we
find that tcalc is greater than ttable at the 95% confidence level, we will state that the
means of the two data sets are significantly different.
However, we have reason to believe that the population standard deviations of
the two data sets are dissimilar. In which case a slightly different method is more
appropriate.
sa2
Fcalc = where sa is the larger of s1 and s2 thus making Fcalc > 1.
sb2
Then in method 2 we use the following formulas to compute tcalc and ttable,
⎛ 2 ⎞
tcalc =
x1 − x2 ⎜
df = ⎜
( s12 /n1 + s22 /n2 ) ⎟
⎟ − 2.
⎜ s 2 /n 2 2
(n 2 + 1) ⎟⎠
s12 / n1 + s22 / n 2 (
⎝ 1 1 ) (n1 + 1) + ( s22 /n2 )
The comparison of tcalc and ttable again tells us that the means of the two data sets
do indeed differ at the 99.5% confidence level.
The formulas required in the worksheet are fairly complex, so it will be bene-
ficial to use meaningful cell names. This makes it easier to compose and check
our formulas than it would be with simple cell references. Using the names in cells
to the left, right or above, make the assignments as shown in table 9.1 where
Rayleigh is the name of the worksheet; changing the sheet’s name will have no
adverse effects.
9-2
Modelling Physics with Microsoft Excel®
Deg_free =Rayleigh!$K$10
F_cal =Rayleigh!$H$11
F_table =Rayleigh!$H$12
Mean_A =Rayleigh!$F$6
Mean_B =Rayleigh!$G$6
n_A =Rayleigh!$F$5
n_B =Rayleigh!$G$5
Dataset_A =Rayleigh!$A$5:$A$12
Dataset_B =Rayleigh!$B$5:$B$12
Pooled_Std_Dev =Rayleigh!$E$10:$E$10
Std_Dev =Rayleigh!$F$7:$G$7
StdDev_A =Rayleigh!$F$7
StdDev_B =Rayleigh!$G$7
t_cal_1 =Rayleigh!$E$11:$E$11
t_cal_2 =Rayleigh!$K$11
t_table_1 =Rayleigh!$E$12:$E$12
t_table_2 =Rayleigh!$K$12
Do not be concerned that the range Dataset_A includes the blank cell A12;
the formulas that use the name will ignore the blank. See the comment at the end
regarding dynamic names.
The formulas are shown in figure 9.3. The one formula that is less than
straightforward is that for F_table in H12. The syntax for F.INV is =F.INV
9-3
Modelling Physics with Microsoft Excel®
DataSet_A = OFFSET(Rayleigh!$A$5,0,0,COUNT(Rayleigh!$A
$5:$A$204),1)
DataSet_B = OFFSET(Rayleigh!$B$5,0,0,COUNT(Rayleigh!$B
$5:$B$204),1).
In this way the user could resize the blue area of the worksheet to accommodate
up to 200 data points in each data set.
9-4
Modelling Physics with Microsoft Excel®
the formula1 for F.INV.RT (cell E10) uses 0.05/2 while the result from F.DIST
(cell E11) is multiplied by 2. Note that F.TEST (cell E13), which is for a two-tailed
test, returns the same value as R.DIST.RT times 2; this gives us confidence that
we are doing things correctly!
In D15:G17 we compare F with F critical, and P with 0.5 within IF formulas and
find that we cannot reject the null hypothesis H0.
To the right in the figure (yellow area) we have the results from using Data | Data
Analysis | F-test Two-Sample for Variances. This tool (figure 9.5) produces the same
results as the formulas (note we again must multiple P by 2 for a two-tailed test
1
Starting with Excel 2010, Microsoft reorganized many statistics functions. The function F.INV.RT replaced
the old function FINV. But rather confusingly, we now have FINV (retained for compatibility) and the new
F.INV function. The moral is: where possible avoid compatibility functions.
9-5
Modelling Physics with Microsoft Excel®
value). Data analysis tools are fine for quick tests and for confirming results
obtained from formulas, but one must always bear in mind that they are static. If we
edited our raw data, the formula would be automatically recalculated, but the static
data analysis results would not; moreover, there is no way of refreshing them other
than starting again.
2
The FREQUENCY function in an array function. The range G2:G22 is selected, the formula =FREQUENCY
(A2:A251,F2:F22) is entered and committed with CTRL+SHIFT+ENTER rather than with the simple
ENTER key. This causes Excel to enclose the formula in curly braces { } in all its cells.
9-6
Modelling Physics with Microsoft Excel®
The quickest3 way to make a chart for comparison purposes is to click anywhere
with in I1:K21 and use the Insert | Charts | Clustered Column Chart. Then right click
the Norm data series in the chart, select Change Chart Type and modify this data
series to a Line chart.
However, displaying the Norm data as an XY chart is preferable since once can
then specify that a smooth curve is needed. Begin by making an XY chart of the data
I1:K21 (see left side of figure 9.7.) Then use Change Chart Type to make a com-
bination chart with the Freq data as a Column and the Norm data as an XY chart.
This will put the Norm data on secondary x- and y-axes. Here are some steps to
follow to generate the chart shown to the right above:
1. on the primary x-axis, specify Axis Position | On Tick Marks;
2. make the secondary bounds the same as the primary bounds for both the
x- and y-axes;
3. when step 2 is completed, hide the secondary axes is by giving the text the
same color as the background. Also hide the tick marks for both secondary
axes by specifying they are to be Inside.
We obtained the frequency data from the raw data. But what if we had been
presented with just the frequency data? We would need to compute the average and
the standard deviation using the formulas:
3
If one wishes to make a column, bar or line chart when the x category values are numeric, it is advisable to
delete the label above the x category data (here the text ‘mid-point’ in I1). This will prevent Excel from using
the first column as a data series and making the chart with categories 1, 2, 3, …. The text can be re-entered
once the chart is made.
9-7
Modelling Physics with Microsoft Excel®
stdev =SQRT((SUM(J2:J21)*SUMPRODUCT(J2:J21,I2:I21^2)-
SUMPRODUCT(J2:J21,I2:I21)^2)/(SUM(J2:J21)*
(SUM(J2:J21)-1)))
The results are shown in table 9.2, together with the error compared to values
from the raw data.
9-8
IOP Concise Physics
Chapter 10
Electrostatics
10-2
Modelling Physics with Microsoft Excel®
The worksheet (figure 10.4) shows a plot of the variable part of the Ex function.
The maximum occurs at about x = 0.7 with the variable portion having a value of
about 0.38.
We can read off the x positions where the values are one-half of this maximum;
these are approximately x = 0.2 and x = 2.0.
1
This problem is adapted from problem 22–78 in [2].
10-3
Modelling Physics with Microsoft Excel®
10-4
Modelling Physics with Microsoft Excel®
10-5
Modelling Physics with Microsoft Excel®
Figure 10.7.
To test the work, we compare (in X9:Y11) the value in C4 with the average of that
cell’s four neighboring cells. The initial results are not encouraging; the difference in
the values for C4 and the average are about 5 × 10−4. However, when we reopen the
FILE | Options | Formula dialog to set Maximum Iterations to 5000 and Maximum
Change to 0.000 000 01, and recalculate the worksheet, we find the two test values
differ by a mere 3 × 10−10—see figure 10.7.
The color effect shown in figure 10.6 was obtained by selecting the range and
applying a Graded Color Scale from the Conditional Format gallery, picking the one
that gives larger values a red shade.
The reader may wish to solve the same problem using Solver following the
method discussed in chapter 4.
References
[1] http://intro.phys.psu.edu/class/212Labs/01_Electric_Charges/Static_Electricity_solutions.pdf
[2] Halliday D, Resnick R and Walker J 2011 Fundamentals of Physics 9th edn (New York: Wiley)
10-6
IOP Concise Physics
Chapter 11
Random events
11-2
Modelling Physics with Microsoft Excel®
For example =RAND()*100 returns a number equal to or greater than 0, but less
than 100. The function RANDBETWEEN(a, b) returns an integer within the range
a–b, inclusive. In all cases a new number is generated every time the worksheet is
calculated; this recalculation can result from entering or editing some other cell,
or from pressing F9. Figure 11.4 shows an example of how the results can be
significantly different after a recalculation.
11-3
Modelling Physics with Microsoft Excel®
In this topic we introduce a worksheet used to find R102 using a VBA program
consisting of several subroutines which closely follow this description. Figures 11.5
and 11.6 show, respectively, the worksheet prior to running the program and after
10 000 conformations have been examined.
11-4
Modelling Physics with Microsoft Excel®
The data in A1:B14 are entered while developing the spreadsheet. In F1 the user
can enter the number of valid conformations that are to be measured. Pressing the
Run Program button begins the process. Values shown in blue are updated
when 100 conformations have been measured, as is the diagram. When the
maximum N values have been examined, the program ceases. Pressing the Reset
button regenerates the chain in its initial state. Note that F8 uses the formula
=SQRT((A14-A4)^2+(B14-B4)^2) to display the value of R for the current
state of the chain; this is merely to check the VBA calculation in E6. The running
11-5
Modelling Physics with Microsoft Excel®
average =Sheet1!$G$6
Chain =OFFSET(Sheet1!$A$4,0,0,COUNT(Sheet1!$A$4:
$A$1000),2)
FirstX =Sheet1!$A$4
length =Sheet1!$E$6
MaxN =Sheet1!$F$1
N =Sheet1!$D$6
Running_time =Sheet1!$E$9:$F$9
totalLength =Sheet1!$F$6
Y_range =OFFSET(Sheet1!$B$4,0,0,COUNT(Sheet1!$A$4:
$A$1000),1)
The buttons are made using Insert | Illustrations | Shapes. The size of, and the text
within a button can be adjusted. A macro can be assigned to a button by right
clicking it and selecting the Assign Macro option. We will briefly examine the VBA
code.
11-6
Modelling Physics with Microsoft Excel®
Randomize
Do While myCount < myN The iteration starts here
Select Case Rnd The fold can happen in 3 directions
Case Is < 0.3333
sintheta = 1 A 360° fold is excluded; mustn’t
Case Is < 0.6666 overlap
sintheta = 0
Case Else
sintheta = -1
End Select
A pivotal mode is selected (not
an end node)
End Sub
11-7
Modelling Physics with Microsoft Excel®
temp = cdata(k, 1)
cdata(k, 1) = cdata(k, 2) * sintheta
cdata(k, 2) = -temp * sintheta
Debug.Print k, cdata(k, 1), cdata(k, 2)
cdata(k, 1) = cdata(k, 1) + xpivot
cdata(k, 2) = cdata(k, 2) + ypivot
Debug.Print k, cdata(k, 1), cdata(k, 2)
Next k
End Sub
Sub checkChain()
Dim k, j
For k = 1 To high - 1
For j = k + 1 To high
If cdata(k, 1) = cdata(j, 1) Then
If cdata(k, 2) = cdata(j, 2) Then
cdata = ctemp
Exit Sub
End If
End If
Next j
Next k
myCount = myCount + 1
myLength = ((cdata(high, 1) - cdata(low, 1)) ^ 2) + ((cdata
(high, 2) - cdata(low, 2)) ^ 2)
myLength = Sqr(myLength)
totalLength = totalLength + myLength
End Sub
Sub ShowData()
Range("chain").Value = cdata
Range("N").Value = myCount
Range("length").Value = myLength
Range("totalLength").Value = totalLength
If myCount > 0 Then Range("average").Value = totalLength /
myCount
end_time = Now()
Range("Running_time") = DateDiff("s", start_time, end_time)
DoEvents
End Sub
11-8
Modelling Physics with Microsoft Excel®
Sub ResetIt()
Dim j As Integer
For j = 1 To Application.Count(Range("A4:A1004"))
Cells(j + 3, "A") = j
Cells(j + 3, "B") = 5
Next j
Range("N").Value = 0
Range("length").Value = 0
Range("totalLength").Value = 0
Range("average").Value = 0
Range("Running_time") = 0
End Sub
References
[1] Einstein A 1905 Über die von der molekularkinetischen Theorie der Wärme geforderte
Bewegung von in ruhenden Flüssigkeiten suspendierten Teilchen Ann. Phys Lpz. 322 549–60
[2] Isaacson W 2007 Einstein: His Life and Universe (New York: Simon & Schuster)
[3] MacDonald B et al 1985 Polymer conformations through ‘wiggling’ J. Phys. A: Math. Gen. 18
2627
11-9