You are on page 1of 96

This content has been downloaded from IOPscience. Please scroll down to see the full text.

Download details:

IP Address: 190.27.239.34
This content was downloaded on 07/01/2015 at 19:44

Please note that terms and conditions apply.


Modelling Physics with
Microsoft Excel®
Modelling Physics with
Microsoft Excel®
Bernard V Liengme

St Francis Xavier University, Nova Scotia, Canada

Morgan & Claypool Publishers


Copyright ª 2014 Morgan & Claypool Publishers

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.

Rights & Permissions


To obtain permission to re-use copyrighted material from Morgan & Claypool Publishers, please
contact info@morganclaypool.com.

ISBN 978-1-627-05419-5 (ebook)


ISBN 978-1-627-05418-8 (print)

DOI 10.1088/978-1-627-05419-5

Version: 20141001

IOP Concise Physics


ISSN 2053-2571 (online)
ISSN 2054-7307 (print)

A Morgan & Claypool publication as part of IOP Concise Physics


Published by Morgan & Claypool Publishers, 40 Oak Drive, San Rafael, CA, 94903, USA

IOP Publishing, Temple Circus, Temple Way, Bristol BS1 6HG, UK


Dedication

To Pauline, my wife and my friend.


Contents

Preface ix
Acknowledgements x
Author biography xi

1 Projectile trajectory 1-1


1.1 Football trajectory 1-1
1.2 Adding air resistance 1-4

2 The pursuit problem 2-1


2.1 The numerical approach 2-1
2.2 Comparison with the analytical solution 2-3
References 2-4

3 Equation solving with and without Solver 3-1


3.1 The van der Waals equation: the fixed point iteration method 3-1
3.2 van der Waals equation: using Solver 3-2
3.3 Finding roots graphically 3-6
3.4 Newton–Raphson method 3-7
3.5 Using Solver to obtain multiple roots 3-8
3.6 The secant method and goal seek 3-10
3.7 The inverse quadratic method 3-11
3.8 Solving systems of linear equations 3-13
3.9 Solving a system of non-linear equations 3-14
3.10 Closing note on Solver 3-15

4 Temperature profile 4-1


4.1 A formula method 4-2
4.2 A matrix method 4-3
4.3 A Solver method 4-5

5 Numerical integration 5-1


5.1 Trapezoid rule and Simpson’s ⅓ rule 5-1
5.2 Centroid of a plane using Simpson’s ⅓ rule 5-3
5.3 Monte Carlo method I 5-4

vii
Modelling Physics with Microsoft Excel®

5.4 Monte Carlo method II 5-5


5.5 Buffon’s needle 5-7
References 5-9

6 Approximate solutions to differential equations 6-1


6.1 Ordinary differential equations (ODEs) 6-1
6.2 Euler’s method 6-1
6.3 The Runge–Kutta method 6-4
6.4 Testing for convergence 6-5
6.5 Systems of ODEs and second-order ODEs 6-7
References 6-10

7 Superposition of sine waves and Fourier series 7-1


7.1 Addition of sine waves; generation of beats 7-2
7.2 Fourier series 7-2
7.3 Parametric plots and Lissajous curves 7-4

8 Fast Fourier transform 8-1

9 Applying statistics to experimental data 9-1


9.1 Comparing averages 9-1
9.2 Comparing variances 9-4
9.3 Are my data normally distributed? 9-6

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

11 Random events 11-1


11.1 Random walk and Brownian motion 11-1
11.2 A random self-avoiding walk 11-4
References 11-9

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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.

1.1 Football trajectory


(Worksheet: Sheet1 in Football.xlsx.) An American football place-kicker must kick
a football from some point on the field, through the uprights and over the crossbar
(10 ft = 3.05 m above the field) for a field goal (3 points). The ball must also clear the
blocking attempts of the opponents, who are approximately 4 m from the kicker and
jumping with their arms raised in the air (approximately 3.5 m).
The relevant formulas are:
x _distance
time =
velocity × cos(angle )
height = velocity × sin(angle ) × time − 1 2g × time 2 ,
where
• g = 9.8 m s−2 is the gravitational constant;
• time is the amount of time elapsed since the kick;
• velocity is the speed of the ball after being kicked;
• x_distance is the horizontal distance traveled down the field by the
football; and
• angle is the angle of elevation (from horizontal) of the kick;
• height is the vertical position of the ball at time t.

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

doi:10.1088/978-1-627-05419-5ch1 1-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 1.1. Football trajectory.

Figure 1.2. Forms control dialog.

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®

Figure 1.3. Data for chart.

The first time value is computed with =P4/(velocity*COS(RADIANS


(angle))).
The first height value with

=IF(velocity*SIN(RADIANS(angle))*R4-g*R4^2/2>=0,
velocity*SIN(RADIANS(angle))*R4-*R4^2/2, NA())

since we wish to avoid plotting negative heights.


Select Q3:R3 and fill down to row 64 by double clicking the fill handle.
It would be reasonable not to plot the trajectory of a ball intercepted by a
defender placed 4 m from the kick. Modify the formula in Q9 (x-dist is 5 m which is
1 m past the defenders) as shown below and fill it down the rest of the column,

=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®

Table 1.1. Formulas for remaining cells.

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.

1.2 Adding air resistance


(Worksheet: Sheet2 in Football.xlsx.) Our first treatment is somewhat incomplete in
that we have neglected the drag caused by the motion of the ball through the air. We
will compare the flight of a ball with and without drag.
For our model we will assume the drag is proportional to the square of the ball’s
velocity, v:
Fdrag = bv 2 .

We need to know the x and y components of this force


Fx − drag = Fdrag cos(θ ) = bv 2 cos(θ ) but vx = v cos(θ )
∴ Fx − drag = bvvx . Similarly, Fy − drag = bvvy.

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.

Figure 1.4. The effect of drag.

1-4
Modelling Physics with Microsoft Excel®

Figure 1.5. Sheet2 of Football.xlsx.

Figure 1.6. Example of extreme drag.

Table 1.2. Formulas for calculations with and without drag.

Without drag With drag

Cell Formula Cell Formula

P3 the value 0 V3 the value 0


Q3 =vinit*COS(RADIANS(θinit)) W3 =vinit*COS(RADIANS(θinit))
R3 =vinit*SIN(RADIANS(θinit)) X3 =vinit*SIN(RADIANS(θinit))
S3 the value 0 Y3 =SQRT(W3^2+X3^2)
T3 the value 0 Z3 the value 0
P4 =P3+dt AA3 the value 0
Q4 =Q3 V4 =V3+dt
R4 =R3-g*dt W4 =W3-b*W3*Y3*dt
S4 =S3+Q4*dt X4 =X3-(g+b*X3*Y3)*dt
T4 =T3+R4*dt Y4 =SQRT(W4^2+X4^2)
P5 =P4+$B$4 Z4 =Z3+W4*dt
Q5 =Q4 AA4 =AA3+X4*dt
R5 =R4-g*dt V5 =V4+dt
S5 =S4+Q5*dt W5 =W4-b*W4*Y4*dt
T5 =IF(T4>0,T4+R5*dt,NA()) X5 =X4-(g+b*X4*Y4)*dt
Y5 =SQRT(W5^2+X5^2)
Z5 =Z4+W5*dt
AA5 =IF(AA4>0,AA4+X5*dt,NA())

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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.

2.1 The numerical approach


Attacking the pursuit problem analytically [1] involves solving a differential equa-
tion, but to use a numerical method we need to invoke a discretization process.
ΔP
Given a problem in the form ddPz = F (z ) we make the approximation Δz = F (z ) and
then use the discrete equation Pn + 1 = Pn + F (z ) Δz . This is known as Euler’s method;
our treatment of the football trajectory in chapter 1 used this technique without
naming it.
We set ourselves the task of constructing the path of the pursuer and the point of
intersection with the pursued. We will work in nameless units with the merchant
vessel moving one length unit per unit of time.
We will advance the merchant by small increments ΔYm and determine the
resulting locations of the pirate. Suppose that at time t the merchant is at (0, Ym)
and the pirate at (Xp, Yp). Since the pirate is pointing directly at the merchant,

doi:10.1088/978-1-627-05419-5ch2 2-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

⎛ 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

Figure 2.1. The pursuit problem.

Table 2.1. Formulas for rows 3 and 4.

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®

Figure 2.2. The approximate and the analytical paths.

merchant, so we add a condition to the formula in I4, namely, =IF(G3<apart,


ATAN((E4-H3)/(D3-G3)),PI()/2); this ensures the pirate travels due north
after intersection.
A XY plot is made using the range G3:H403. Then the range D3:E403 is copied
and pasted to the chart as a new series—see the left panel of figure 2.2.

2.2 Comparison with the analytical solution


The ‘curve of pursuit’ is a topic in many calculus books [2] and websites [3], in
addition to reference [1] which gives the equation of the curve as

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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.

doi:10.1088/978-1-627-05419-5ch3 3-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 3.1. The iteration method.

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 van der Waals equation: using Solver


We now perform the same calculation but using Solver which we will set up to make
the left and right sides of the equation below have the same value:
⎛ a ⎞
⎜ P + 2 ⎟ ( Vm − b) = RT.
⎝ Vm ⎠

3-2
Modelling Physics with Microsoft Excel®

Figure 3.2. The Solver method.

(Worksheet: Sheet2 in EqnSolving.xlsm.) As shown in figure 3.2, we begin in much


the same way as above, with the data in B7:B11. In B13 we compute V from the ideal
gas law. We then type into B16 the value we see in B13 (rounding off to an integer is
OK). The two sides of the equation are coded as B17: =(P + a/B16^2)*(B16-b)
and B18: = R_*T. Then using Data | Analysis | Solver we open the Solver dialog and
complete as shown in figure 3.3.
The first task is to specify a constraint precision setting more demanding than
the default. Click the Options button and change the Constraint Precision (figure 3.4)
to 0.000 000 001 (i.e. 1.0E-9). Return to the main Solver dialog and press Solve. As
expected, the result is essentially the same as the one we obtained with the successive
approximation method.
The Solver result is not dynamic; if we set a new problem (different P and T
and/or different van der Waals constants) we will have a worksheet displaying the
wrong answer. To this end, in A19 we use the formula =IF(ABS(B17-B18)
<0.000001,"Solved","Not Solved"). Furthermore, to draw our attention
to this, we have used conditional formatting on A19 (the merged cells A19:C19).

3-3
Modelling Physics with Microsoft Excel®

Figure 3.3. The Solver dialog.

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®

Figure 3.4. Solver options dialog.

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®

Figure 3.5. Solver—the incorrect method.

Figure 3.6. Getting roots graphically.

3.3 Finding roots graphically


This technique is generally taught in high school but here we use some interesting
Visual Basic for Applications (VBA)3 to make life a little easier. For the sake of
clarity we will work with a polynomial with integer coefficients.
(Worksheet: Sheet 4 in EqnSolving.xlsm.) Our task is to find the roots of the
polynomial f (x ) = x 6 − 4x5 + 4x 4 − x 2 + 4x − 4. Clearly, by examining the

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.

3.4 Newton–Raphson method


The Newton–Raphson method of finding roots is also an iterative method. We have
a function f (x) whose roots we wish to discover. We make a guess x 0 at the root and
compute a better estimate x1 using xn + 1 = xn − f (xn )/f ′ (xn ). We repeat the pro-
cedure until f (x) is zero or as close as required.
(Worksheet: Sheet5 in EqnSolving.xlsm.) Figure 3.7 shows a worksheet set up to
find the roots of f (x ) = x 6 − 4.125x5 + 3.75x 4 − x 2 + 4x − 5. This is the function
referred to in the experiment above and graphically we know them to be approx-
imately −1.5 and 3. The first value has been used as the x 0 in the left side (the ecru
colored area) and the second in the right side (the blue area). The relevant formulas are:
f (x 0) is found in C4 with = B4^6 -4.125*B4^5 + 3.75*B4^4 - B4^2 +
4*B4 -5;
f ′(x 0) is found in D4 with =6*B4^5 -(5*4.125)*B4^4 + (4*3.75)*B4^3
- 2*B4 + 4.

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®

Figure 3.7. Newton’s method.

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.5 Using Solver to obtain multiple roots


(Worksheet: Sheet6 in EqnSolving.xlsm.) Figure 3.8 shows a worksheet set up to find
the two real roots of f (x ) = x 6 − 4.125x5 + 3.75x 4 − x 2 + 4x − 5. This is the same
f (x) whose roots we found above by the Newton method.
For the moment ignore columns D and E. In A4 and A5 we have two starting
values for Solver to work with. In B4 we have = A4^6 -4.125*A4^5 +
3.75*A4^4 - A4^2 + 4*A4 -5 and this is copied down to B5.
Solver is set up as in figure 3.9 and the constraint precision has again been set to
1 × 10−9. It is very important to note that the box Make unconstrained variables non-
negative has been unchecked—we are expecting A4 to stay negative. When Solver is

3-8
Modelling Physics with Microsoft Excel®

Figure 3.8. Multiple roots in Solver.

Figure 3.9. Solver dialog with constraint.

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.6 The secant method and goal seek


The secant method for finding roots requires two initial values (x 0 and x1) rather
than one as in the Newton–Raphson method. It uses the recurrence formula
x n − 2 f (x n − 1 ) − x n − 1 f (x n − 2 )
xn = .
f (x n − 1 ) − f (x n − 2 )
(Worksheet: Sheet7 in EqnSolving.xlsm.) The left side of figure 3.10 shows a
worksheet set up to find the root of f (x ) = x 6 − x − 1 in the interval [1,2] using the
secant method. Initial x 0 and x1 values were entered into A5 and A6 while B5 and
B6 compute the values of f (x 0) and f (x1) with the formula = A5^6-A5-1 in B5
which is then copied to B6. The x2 value is estimated in B7 with the Excel imple-
mentation of the secant method, namely=(A5*B6-A6*B5)/(B6-B5). After
copying B6 to B7, we select A7:B7 and drag the fill handle down. Note how by row
15 we have an essentially zero value for f (x 0). We have dragged down one row to
far: since f (x10) and f (x11) are the same, the denominator in the secant formula is
zero so we get a #DIV/0! error in A17.
For the sake of completeness we will briefly look at Excel’s Goal Seek tool,
although once one has mastered Solver, Goal Seek seems a bit lame.
Enter some starting value in D8 (say, 1) and copy the f (x) formula from B5 to E8.
After clicking on E8, open the Goal Seek dialog with the command Data | Data

Figure 3.10. Goal Seek.

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.

3.7 The inverse quadratic method


The inverse quadratic method for finding roots requires three initial values (x 0, x1
and x2). It uses the following recurrence formula:
f ( xn − 1)f ( xn )xn − 2 f ( xn − 2 ) f ( xn ) xn − 1
xn = +
( f ( xn −2 ) − f ( xn −1))( f ( xn −2 ) − f ( xn )) ( f ( xn −1) − f ( xn −2 ))( f ( xn −1) − f ( xn ))
f ( xn − 2 )f ( xn − 1)xn
+ .
( f ( xn ) − f ( xn −2 ))( f ( xn ) − f ( xn −1))
There is an alternative way of presenting this:
Let a = xn , b = xn + 1 and c = xn + 2 .

Let u = f (b)/ f (c ), v = f (b)/ f (a ) and w = f (a )/ f (c ).


Let p = v (w (u − w)(c − b) − (1 − u )(b − a ) and q = (w − 1)(u − 1)(v − 1).
Then xn + 3 = b + p / q .

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:

Function fx(x) Function InvQuad(a, b, c)


fx = x ^ 2 - 4 * Sin(x) u = fx(b) / fx(c)
End Function v = fx(b) / fx(a)
w = fx(a) / fx(c)
p = v * (w * (u - w) * (c - b) - (1 - u) * (b - a))
q = (w - 1) * (u - 1) * (v - 1)
InvQuad = b + p / q
End Function

5
The code is in Module 2 of the workbook EqnSolving.xlsm.

3-11
Modelling Physics with Microsoft Excel®

Figure 3.11. Roots using the inverse quadratic method.

Figure 3.12. The input box dialog.

(Worksheet: Sheet8 in EqnSolving.xlsm.) Figure 3.11 shows a worksheet set up to


find the roots of f (x ) = x 2 − 4 sin(x ). Of course, the f (x) function can be edited to
solve other problems. The yellow area holds our starting data while the blue area
uses the inverse quadratic interpolation method. To the sides we have the values or
formulas in each cell. The value of f (x) in C12 is essentially zero; indeed if we
continue any further we will get a #VALUE! error. So the root, displayed to six
decimal places, is 1.933 754.
(Worksheet: Sheet9 in EqnSolving.xlsm.) Figure 3.12 shows a worksheet set up to
show only the results of the inverse quadratic interpolation method. Clicking the

3-12
Modelling Physics with Microsoft Excel®

Figure 3.13. Matrix method for systems of linear equations.

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.

3.8 Solving systems of linear equations


The simplest way to solve a system of linear equations is the matrix method. Suppose
we have a system of equations as represented by
⎡ a11 a12 … ⎤ ⎡ x1 ⎤ ⎡ c1 ⎤
⎢ a21 a22 … ⎥ ⎢ x2 ⎥ = ⎢ c2 ⎥
⎣… … … ⎦ ⎣… ⎦ ⎣… ⎦
which we may write as AX = C. Then we perform the following matrix algebra: (1)
multiple by the inverse of matrix A to give A−1AX = A−1C; (2) simplify this to IX =
A−1C, or X = A−1C. So we can find the X matrix by multiplying A−1 by C.
(Worksheet: Sheet10 in EqnSolving.xlsm.) This method is shown in figure 3.13 for
the system of equations for a circuit analysis problem. Matrix A (blue area) holds the
coefficients for the equations. The pink area computes the inverse of A using the
array formula7 = =MINVERSE(F17:H19). The green area contains the constants
for each equation. In the yellow area we solve the system of equations using the
array formula = MMULT(F22:H24,J22:J24). The reader may wish to experiment
with nesting the MINVERSE within the MMULT, thereby making the pink area
unnecessary.

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.

3.9 Solving a system of non-linear equations


A system of non-linear equations may be solved by one of several iterative methods
including the Newton–Raphson method. This, however, is somewhat complicated for a
beginning physics student. An internet search discovered a clear explanation8 of the
method for the problem set out below; we will see how to use Solver to solve the system.
Solve the set of non-linear equations
f1 (x1, x2 ) = 4 − (x1 − 3)2 + 0.25x1x2 − (x2 − 3)2 = 0

f2 (x1, x2 ) = 5 − (x1 − 2)2 − (x2 − 2)3 = 0.

(Worksheet: Sheet10 in EqnSolving.xlsm.) Figure 3.15 shows a worksheet set up


to solve the problem. The blue area contains the variable; cells B4 and B5 have

Figure 3.14. Solver method for systems of linear equations.

Figure 3.15. Solver method for systems of non-linear equations.

8
David R Levin http://tx.technion.ac.il/~dlewin/054374/Day_5.pdf.

3-14
Modelling Physics with Microsoft Excel®

Figure 3.16. Solver dialog for Sheet10.

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.

3.10 Closing note on Solver


It was stressed above that one should always run Solver a second time. One can
also experiment with the GRD Nonlinear Convergence option setting (figure 3.17).

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®

Figure 3.17. Solver convergence setting.

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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

Figure 4.1. Thermal equilibrium.

doi:10.1088/978-1-627-05419-5ch4 4-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

approximation. We shall consider a finite number of equidistant points on the plate


and use the discrete mean-value theory, which states that the temperature at point
P is the average of the temperatures of P’s nearest neighbors.
The most convenient way to arrive at the equidistant point is to divide the plate
using equally spaced vertical and horizontal lines. In figure 4.1 two such lines have
been drawn parallel to each axis. This gives four interior points for the calculation.
With such a small number, the results will not be very accurate. However, the
methodology is the same regardless of the number of points, and it is simpler to
describe and test the method initially with four points.

4.1 A formula method


(Worksheet: TempCirr in TemperatureProfile.xlsx.) We begin by setting up a
worksheet as shown in figure 4.2. In this model we are working with 16 interior
points rather than the 4 shown in the figure above. Type the formula =AVERAGE
(C4,D5,C6,B5) into C5 and drag it across and down to fill C5:F8. All other cells
contain literal values. We are not surprised that Excel warns us of a circular error.
When the author set up the worksheet there were blue arrows between F5 and F6
and the status bar warned of a circular error in F4; of course, there are numerous
circular errors. Initially, cells C5:F8 all displayed the value 150, but if one double
clicks a cell its value can change.
Circular errors are normally to be avoided but in the right circumstances they can
be useful; this is one of those occasions. Within the FILE tab open the Options dialog
and open the Formula tab in the resulting dialog—figure 4.3. Set the calculation
mode to Manual and check the Enable Iterative Calculations box. Return to the
worksheet after clicking the OK button.
Press the F9 key several times until the values in C5:F8 cease to change.
Figure 4.4 shows the final outcome.
IMPORTANT: you must remember to return to FILE | Options | Formulas and
select Automatic calculations and uncheck the Enable Iterative Calculations box.

Figure 4.2. Temperature profile using circular referencing.

4-2
Modelling Physics with Microsoft Excel®

Figure 4.3. Configuring Excel for iteration.

Figure 4.4. Circular referencing results.

4.2 A matrix method


(Worksheet: TempMatrix 2 × 2 in TemperatureProfile.xlsx.) We begin with a model
with just four interior points. We will set up a system of linear equations and use
matrix mathematics to solve them.
Applying the averaging rule, the temperatures of the four interior points are given by:
t1 = ( 100 + t2 + t3 + 200) /4
t2 = ( 100 + 100 + t 4 + t1) /4
t3 = ( t1 + t 4 + 200 + 200) /4
t 4 = ( t2 + 100 + 200 + t3 ) /4.

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.

We may write this system of four equations as T = MT + B.


We can rearrange this to give T − MT = B which leads to (I − M)T = B where I is the
identity matrix, a matrix in which the diagonal elements are 1 and the off-diagonal
elements are 0; this may be generated in Excel 2013 with the MUNIT() function.
So to solve for T we use: T = (I − M)−1 B.
In figure 4.5, the cells A4:D4 are named using the text in the row above. The cells
in the M matrix range (A8:D11) contain the coefficients of the system of equations
while the B matrix contains the non-variable parts. For example in F8 we use
=(SideA+SideD)/4. The range A15:D18 was selected and the array formula
=MINVERSE(MUNIT(4)-A8:D11) was entered and committed with CTRL +
SHIFT + ENTER. The solutions to the system of equations is found in G15:G18
with the array formula =MMULT(A15:D18,F8:F11).
In the lower part of the worksheet we prove to ourselves that the resulting
T vector results are indeed the averages of the nearest-neighbor pairs.

Figure 4.5. Temperature profile using matrix algebra.

4-4
Modelling Physics with Microsoft Excel®

Figure 4.6. Charting the results.

(Worksheet: TempMatrix 4 × 4 in TemperatureProfile.xlsx.) Encouraged by the


results with a simple model we expand to use a 4 × 4 grid. The results are shown in
figure 4.6. Note that they are (happily!) in total accord with the circular reference
method.

4.3 A Solver method


Both the circular reference formula and the matrix methods could be expanded to
use a finer grid but the user would be required to do much work. We will now
demonstrate a Solver method which is more readily expanded. However, the Solver
add-in that comes with Microsoft Excel is limited to 200 variables. The commer-
cially available Premium Solver Pro add-in1 can handle 2000 variables.
(Worksheet: TempSolver in TemperatureProfile.xlsx.) We will show how to solve
the 4 × 4 model. The worksheet is set up initially as shown in figure 4.7. The values
in C5:F8 (blue region) are our initial ‘guesses’. This range has been named
Variables and will be used as the By Changing Variables cells in the Solver set up.
In C13 we have the formula =AVERAGE(C4,D5,C6,B5) and this is copied to fill
C13:F16 (the yellow area) which has been named Solutions. These will be used to
construct a constraint in the Solver set up.
Solver is invoked and the model is set up as shown in figure 4.8; note that the Set
Objective box is blank. We are asking Solver to compute values in the Variables
range such that they are equal to values in the Solutions range. For example, we

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®

Figure 4.7. Temperature profile using Solver.

Figure 4.8. Solver setup for temperature profile.

4-6
Modelling Physics with Microsoft Excel®

Figure 4.9. Solver results for temperature profile.

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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.

5.1 Trapezoid rule and Simpson’s ⅓ rule


In the trapezoid method the area under the curve is divided into a number of strips
(or segments) defined by two data points on the curve. The area of a single strip is the
1
average height × base, or area = 2 (yi + 1 − yi )(xi + 1 − xi ) where xi, yi and xi+1, yi+1 are
the coordinates of two points on the curve. If we have data that are equally spaced
on the x-axis we may use
n
1
I≈ ∑ 2 (yi + 1 + yi )Δx.
i=1

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

doi:10.1088/978-1-627-05419-5ch5 5-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 5.1. Trapezoid and Simpson’s ⅓ rule.

Table 5.1. Formulas for E4:F6.

Cell Formula Cell Formula

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®

5.2 Centroid of a plane using Simpson’s ⅓ rule


The coordinates (x , y ) of the centroid of a plane region bounded by f (x) and g(x) = 0
in the interval [a, b] may be computed from the equations
1 b 1 b b
x =
A a
∫ xf (x )dx y =
2A a

f 2 (x )dx where A =
a
f (x )dx. ∫
Clearly A is the area of the region.
One way of representing the Simpson’s ⅓ rule with x values incremented by h is
⎡ n /2 − 1 n /2 ⎤
h⎢
S= f (x0) + 2 ∑ f (x2j ) + 4∑ f (x2j − 1) + f (xn )⎥
3 ⎢⎣ j=1 j=1
⎥⎦

which we will call the compact form.


(Worksheet: Sheet2 in Integrate.xlsm.) In figure 5.2 we have some tabulated data
(A3:B14) giving points on a plane region for which the centroid position is needed. We
use the compact form1 of Simpson’s rule in B17, C17 and D17 to compute the required
integrals. Then in B20 and C20 we find the coordinates. Our formulas are as follows.

For A in B17: =(1/3)*(B4+B14+4*(B5+B7+B9+B11+B13)+2*(B6+B8


+B10+B12)).
For Ix in C17: =(1/3)*(C4+C14+4*(C5+C7+C9+C11+C13)+2*(C6+C8
+C10+C12)).

Figure 5.2. Locating the centroid with Simpson’s rule.

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®

For Iy in D17: =(1/3)*(D4 +D14+4*(D5+D7+D9+D11+D13)+2*(D6+D8


+D10+D12)).
For x̄ in B20: =C17/B17.
For ȳ in C20: =(1/2)*D17/B17.
This, of course, is a test case; the data were generated from f(x) = −0.5x3 +
4x + 10x. So we are able to evaluate the three integrals analytically2 and compute the
2

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®

Figure 5.3. Monte Carlo method for integration.

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.4 Monte Carlo method II


The second Monte Carlo method again uses the area analogy but this time it is in the
form Area = Average height of curve × Width of base.

5-5
Modelling Physics with Microsoft Excel®

Figure 5.4. Alternative Monte Carlo method.

(Worksheet: Sheet4 in Intergration.xlsm.) In this worksheet (figure 5.4) 2000


random values in the range 0–π/2 are generated in B9:B2008. The sample
formula in B9 is = RAND() * PI()/2. In C9:C2008 the y-value for the function (i.e.
the height of the curve above the base for the given x value) is computed; the sample
formula in C9 is = SIN(2 * B9) * EXP(1-COS(2 * B9)). In D4 the formula
= (PI()/2) * AVERAGE(C9:C2008) computes the approximation for the area.
Once again pressing F9 will generate new values in column B and hence a new
approximation. Please do not compare the value with the Monte Carlo method I
above; the two screen shots appear to show method II to be superior but by pressing
F9 repeatedly one can get a set of random numbers that give an error value in
method II that exceeds than shown for method I.
As with method I, the worksheet also includes the results from a UDF. In G6 we
have = MonteArea2(F6). The MonteArea2 UDF is shown below. Like the
worksheet method, it computes n random x values, generates the f (x) value and
concludes by finding the average f (x) value which it then multiples by the base to
give the approximate area.

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

5.5 Buffon’s needle


We will switch gears slightly and use a known definite integral to approximate π with
a statistical method.
In 1733 Buffon posed the problem of finding the probability that a needle, when
dropped onto a surface having equidistant parallel lines, would touch any line. He
proposed a solution in 1777 [2]; his death on the guillotine for being a royalist
prevented further mathematical endeavors.
The position of a dropped needle relative to the nearest line can be summed up by two
parameters: the distance (D) of the center of the needle from the line, and the angle (θ) the
needle makes to an imaginary line running parallel to the drawn lines—see figure 5.5.
We will consider just the simple case in which the length of the needle and the distant
between pairs of lines are the same; we will treat this as one unit of length.
Clearly, D can range from 0 to 1 , while θ can be in the range 0–π. For the needle
2
to touch the line it is necessary that D ⩽ 1 sin(θ). In figure 5.6 we have the curve of
2
1
and a rectangle encompassing all possible D and θ values. The probability of
sin(θ)
2
touching a line is given by (area under the curve) / (area of rectangle):

π
∫0 1
2
sin(θ )dθ
1 2
prob = 1
= = = 0.6366197
×π π /2 π
2

Figure 5.5. Buffon’s needle.

5-7
Modelling Physics with Microsoft Excel®

Figure 5.6. Possible D values.

Figure 5.7. Buffon’s needle worksheet.

Table 5.2. Formulas for B7:F7.

Cell Formula Instruction

B7 = buffA(n) This is copied down to B16


C7 = 2/B7 This is copied down to C16
D7 = AVERAGE(C7:C16)
E7 = PI()
F7 = (D7-E7)/E7

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®

The cell C4 has been named as n representing the number of needles to be


dropped in each of 10 experiments. The formulas in B7:F7 are shown in table 5.2.
The VBA code for the function buffA is:

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

Chapter 6
Approximate solutions to differential equations

6.1 Ordinary differential equations (ODEs)


We are given the expression for a differential equation in the form dy/dx = f(x)
together with an initial value y(x0) = k. Our task is to find an approximation for y at
some other x value.

6.2 Euler’s method


This is the oldest of the methods to find an approximate solution to an ordinary
differential equation. We are given a first order differential equation in the form
dy
dx
= f (x, y ) together with some initial value such as the value of y(0) and our task is
to find an approximate value for y at some other x value, xn. The reader should
consult a textbook on numerical methods to find the justification for Euler’s method
(also called the tangent method). It uses the iteration shown below with h being the
step size; generally we experiment with ever decreasing h values until the desired
precision is obtained.
yi + 1 ≈ yi + f (x , y ) h or yi + 1 ≈ yi + y′h for i = 1, 2, … , n − 1,
where n = ( i ( xn ) − y (0) ) / h .

(Worksheet: Euler1 in DiffEquations.xlsm.) Figure 6.1 shows a worksheet set up


2y − 18x
to find y(2) given y′ = 1 + x and y(0) = 4. The exact solution [1] for this is
y = − 5x 2 + 8x + 4.
Column A is merely a series of numbers to tell us how many steps we have made.
In C6 we have the first h value. The formulas in B8:D9 are shown in table 6.1.
Cells B9:D9 are dragged down until we have a final x value of 2.
To generate the second data set one copies B8:D9 to G8 and drags G9:I9 down
until we have a final x value of 2. The use of the mixed reference C$6 in the D8
formula means that when it is copied to I8 it will then reference H$6. Two other data

doi:10.1088/978-1-627-05419-5ch6 6-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 6.1. Euler’s approximation.

Table 6.1. Formulas for cells B8:D9.

Cell Formula Description

B8 the value 0 the initial x-value


C8 =$C$4 the value of y(0)
D8 =C$6*(2*C8-18*B8)/(1+B8) this corresponds to f (x, y)h
B9 =B8 + C$6 x is incremented by h
C9 =C8 + D8 y1 = y0 + f (x, y)h
D9 =C$6*(2*C9-18*B9)/(1+B9) this comes from copying D8

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®

Figure 6.2. Euler’s approximation results.

Figure 6.3. Euler’s approximation using VBA.

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!

6.3 The Runge–Kutta method


The reader should consult a numerical methods textbook for the theory behind the
various Runge–Kutta methods. We will explore the fourth-order method; this is
sometimes called the RK4, the ‘classical’ or simply ‘the’ Runge–Kutta method as it
is the more popular of the methods. The RK4 method uses the formulas1 shown
dy
below to solve first order differential equations in the form dx = f (x, y ) subject to a
given initial value:

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®

Figure 6.4. Runge–Kutta approximation.

Table 6.2. Formulas for cells B9:H10.

Cell Formula Cell Formula

B9 =x0 B10 =B9+h


C9 =y0 C10 =C9 + (h/6)*(D9 + 2*E9 + 2*F9 + G9)
D9 =DiffEqn(B9,C9) D10 =DiffEqn(B10,C10)
E9 =DiffEqn( (B9+h/2), E10 =DiffEqn( (B10+h/2),
(C9 + D9*h/2)) (C10 + D10*h/2))
F9 =DiffEqn( (B9+h/2), F10 =DiffEqn( (B10+h/2),
(C9+E9*h/2)) (C10+E10*h/2))
G9 =DiffEqn( (B9+h), G10 =DiffEqn( (B10+h), (C10+F10*h))
(C9+F9*h))
H9 =-5*B9^2+8*B9+4 H10 =-5*B10^2+8*B10+4

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.4 Testing for convergence


We have seen that as h gets smaller the results for y converge to the point where
further reduction is unproductive. In the section above we saw how to test the
convergence of the Euler method. Figure 6.5 (worksheet RK Converge in
DiffEquations.xlsm) shows the result of halving the h value nine times for the same
problem as in the previous workbook.

6-5
Modelling Physics with Microsoft Excel®

Figure 6.5. RK approximation showing convergence.

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

x=x+h ‘increment x for the next y value


Next m

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

6.5 Systems of ODEs and second-order ODEs


To solve for a system of ODEs one just expands the RK4 formulas. So, for two
simultaneous equations, one would use the following:

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®

To solve a second-order ODE one makes an appropriate substitution that gives a


pair of simultaneous first-order ODEs. For example, to solve y″ = y′ + y = sin(x)
subject to y(0) = 0 and y′(0) = 0, one can make the substitution y′ = u, to get a pair
of equations y′ = u with initial value y(0) = 0 and u′ = sin(x) − y − u with initial
value u(0) = 0.
Consider a rocket of mass M subjected to an upward thrust T caused by ejecting
matter at a rate m per second. If atmospheric drag is excluded, the second-order
ODE [2] giving the vertical altitude y is

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

(Worksheet: RungeKutta2 in DiffEquations.xlsm.) Figure 6.6 shows a work-


sheet set up to solve this system of equations with the numerical values M = 100 kg,
T = 10 000 N, m = 5 kg s−1 and g = 9.8 m s−2.
The cells in A4:D4 are named with the text in the row above. The formulas in
rows 7 and 8 are shown in table 6.3.
The code for the UDF is:

Function Rocket(t)
Rocket = 10000 / (100 - 5 * t) - 9.8
End Function

Figure 6.6. Second-order differential equation.

6-8
Modelling Physics with Microsoft Excel®

Table 6.3. Formulas for rows 7 and 8.

Cell Formula Cell Formula

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

Figure 6.7. Comparing approximations with analytical results.

6-9
Modelling Physics with Microsoft Excel®

The exact solutions2 are


T ⎛⎜ mt ⎞⎟
u (t ) = − ln 1 − − gt = − 1000 ln(1 − 0.05t ) − 9.8t
m ⎝ M⎠
M ⎛ T ⎞ ⎛⎜ mt ⎞⎟ ⎛⎜ mt ⎞⎟ T
y (t ) = ⎜ ⎟ 1 − ln 1 − + − 1 2gt 2

m m ⎠ ⎝ M ⎠ ⎝ M⎠ m
= 10000(1 − 0.05m) ln(1 − 0.05m) + 2000t − 4.9t 2.
The RK4 calculations are in excellent agreement with the exact values; this is
demonstrated by the chart in figure 6.7.

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

Chapter 7
Superposition of sine waves and Fourier series

(Worksheets: Sheet1 and Sheet2 in SineWave.xlsx.) We begin by plotting a simple


sine wave y = A sin(2πft ). Initially this seems a trivial task but as we start to make
the worksheet we wonder ‘how many points do I need?’ or ‘what value shall
I use for the t increment?’ Figure 7.1 shows four plots with decreasing time incre-
ment values; the increments are 1/(Factor × f ). From this we learn that the time
increment should be equal to or smaller than 1/12f. An alternative way of saying this
is: you need at least 12 points for a full cycle: 0° to 360°. On Sheet2 of the workbook
there is a chart comparing sine waves made with spacing 1/12f and 1/24f.

Figure 7.1. Sine waves-sampling comparisons.

doi:10.1088/978-1-627-05419-5ch7 7-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 7.2. Addition of sine waves.

7.1 Addition of sine waves; generation of beats


(Worksheet: Sheet3 in SineWave.xlsx.) Figure 7.2 shows two sine waves together
with their summation. This demonstrates how beats are formed by two sound waves.
On the worksheet we can vary both the frequency and the amplitude of wave B
relative to wave A using two scroll bar form controls. The first control is linked to
cell F3 (hidden by the control); by sliding the control, values from 0 to 50 may be
given to F3. Cell E3 contains the formula =F3/25 giving it the range 0–2. The
frequency of wave B is governed by the formula =B3*E3 in cell C3. In a similar
manner, the second control may be used to adjust the amplitude of the wave B. The
video FormControl.mp4 shows how a form control may be added to a worksheet
and linked to a cell. Note: the time increment (delta) is set by the larger frequency
using the formula =1/(12*MAX(B3:C3)).
(Worksheet: Sheet4 in SineWave.xlsx.) This sheet expands on the same topic but
includes the ability to alter the phase of wave B relative to wave A from 0 to 2π
radians—see figure 7.3.

7.2 Fourier series


It is convenient in problems connected with vibrations, oscillations and other
periodic functions where phenomena are repeated over and over, to describe the
phenomenon using a combination of sine and cosine terms. Euler, Bernoulli and
others studied this topic, but the name normally associated with it is Joseph
Fourier.

7-2
Modelling Physics with Microsoft Excel®

Figure 7.3. Fourier series-sine wave.

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

The a and b coefficients are calculated using:


1 2L 1 2L ⎛ nπx ⎞ 1 2L ⎛ nπx ⎞
a0 =
2L
∫0 f (x )dx an =
L
∫0 f (x )cos⎜
⎝ L ⎠
⎟dx bn =
L
∫0 f (x )sin⎜
⎝ L ⎠
⎟dx .

(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®

Figure 7.4. Fourier series-triangular wave.

Figure 7.5. Parametric plotting.

7.3 Parametric plots and Lissajous curves


(Worksheet: Sheet6 in SineWave.xlsx.) The most convenient way to plot a circle or
an ellipse is with a parametric plot. The parametric equations for an ellipse are:

x = a sin(θ ) ⎫
⎬ 0 < θ < 2π .
y = b cos(θ )⎭

For a circle, of course, a = b.


In figure 7.5 the range A7:A47 has θ value from 0 to 2π in steps of π/20 while
cells B7 and C7 hold the formulas =aSIN(A7) and =bCOS(A7), respectively, and
these are copied down to row 47. The parameters are in B4 and C4; these cells

7-4
Modelling Physics with Microsoft Excel®

Figure 7.6. Lissajous curve worksheet.

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®

Figure 7.7. Examples of Lissajous curves.

7-6
IOP Concise Physics

Modelling Physics with Microsoft Excel®


Bernard V Liengme

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

Figure 8.1. Input signal and its PSD diagram.

1
The author is grateful to Doug Godsoe, PhD, PEng for assistance with this tool.

doi:10.1088/978-1-627-05419-5ch8 8-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 8.2. Generating sample input data.

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®

Figure 8.3. Results of the Fourier analysis.

Figure 8.4. Fourier analysis dialog.

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

Chapter 9
Applying statistics to experimental data

9.1 Comparing averages


In this topic we explore how to answer the following questions about two data sets:
(a) are the means (averages) significantly different? and (b) are the variances statis-
tically different?
In 1894, Lord Rayleigh lectured the Royal Society on the difference in the mass of
a certain volume (at the same T and P) of nitrogen gas derived from chemical and
atmospheric sources. This difference was explained in terms of a new, hitherto
undiscovered element. Sir William Ramsay (an analytical chemist who worked for
Bunsen) later isolated this element, which he called argon.
(Worksheet: Rayleigh in Statistics.xlsx.) In columns A and B of figure 9.1 we see
the two data sets. From figure 9.2 we intuitively feel that the means differ, but we
wish to confirm this using statistics.
We begin by computing the mean and standard deviation of each data set in E3:
G7; these are required for each of the two methods we shall pursue.
In method 1 we compare the two means by computing a Student’s t-test value and
comparing this with the so-called table value for the t-test. The formula for the
computed value is
x1 − x2 n1 n 2 s12 (n1 − 1) + s22 (n 2 − 1)
tcalc = where sspooled = .
sspooled n1 + n 2 n1 + n 2 − 2

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.

doi:10.1088/978-1-627-05419-5ch9 9-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 9.1. The Argon worksheet.

Figure 9.2. Raleigh’s statistics.

We confirm that population standard deviations differ with an F-test. Fcalc is


found using the formula below and this is compared with Ftable which is found with
the Excel F.INV function,

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®

Table 9.1. Cell names and assignments.

Cell name Assignment

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

Figure 9.3. Formulas for the worksheet.

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®

(probability, deg_freedom1,deg_freedom2) where deg_freedom1 is


associated with the data set with the larger standard deviation value. We could use
=F.INV(95%,n_B - 1, n_A -1) since we know the B data set has the larger
standard deviation. However, to make the formula more general we have used:

=F.INV(95%,INDEX(F5:G5, MATCH(MAX(Std_Dev), Std_Dev,0))-1,


INDEX(F5:G5, MATCH(MIN(Std_Dev), Std_Dev, 0))-1).

The MATCH(MAX(Std_Dev),Std_Dev,0) part finds the cell within F7:G7


that has the larger s value; its position is 2. The first INDEX part now becomes
INDEX(F5:G5, 2) which picks up the second n value in F5:G5, namely 8; from
this 1 is subtracted to compute deg_freedom1. The website www.contextures.
com/xlFunctions03.html is a good place to learn more about the use of MATCH
within an INDEX formula. An alternative formula for F_table is =F.INV
(95%,IF(StdDev_A>StdDev,n_A, n-B) -1, IF(StdDev_A<StdDev, n_A,
n-B) -1).
Dynamic names: as constructed, this worksheet may be used with data sets having
up to eight values. If we wish to make it more general we could change the
definitions of DataSet_A and DataSet_B to

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.2 Comparing variances


It is sometimes useful to compare the variance of two data sets. Example 1: we have
two data sets reporting measurements of the same quantity but made by two dif-
ferent methods (or two testing labs) and we wish to know if one method (one lab) is
more precise than the other. Example 2: we have samples from two sources and wish
to know if they are representative of similar or different populations.
We will perform a two-tailed test for the hypotheses H0: σ12 = σ22 and HA: σ12 ≠ σ22
at the 95% (α = 0.05) significance level. For such a test the data set with the larger
variance is chosen as data set 1.
We must also bear in mind that most of Excel’s F functions give results for one-
tailed tests so we must remember to use a factor of 2 in some equations.
(Worksheet: F-test in Statistic.xlsx.) Looking at figure 9.4, in A3:B14 (the blue
area) we have the actual data while in D3:F7 (the orange area) we have some sta-
tistics for each data set. From these statistics we compute the F value in E9. In E10
and E11 we compute the critical F value and the probability, respectively. Since
we wish to find F critical for a two-tailed test for α = 0.05, our first argument in

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

Figure 9.4. An F-test example.

Figure 9.5. The F-test dialog.

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.

9.3 Are my data normally distributed?


We will briefly look at how we can display the distribution of experimental data and
compare it to the normal distribution (aka the bell curve).
(Worksheet: BellCurve in Statistics.xlsx.) In figure 9.6 some of the 250 data points
are shown in column A. Some descriptive statistics are calculated in column D.
Bin values have been entered in column F and the FREQUENCY function2
is used in column G. Mid-point values have been entered into column I and the
frequency values in column I are picked up from column G with formulas such as
=G3. The normal probability values are computed in column K; the formula in K2 is
=NORM.DIST(I2,$D$4,$D$5,FALSE)*250*0.5 where the last two factors are
(i) the size of the data set and (ii) the size of each bin.

Figure 9.6. Testing for normal distribution.

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®

Figure 9.7. Charting normal distribution.

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:

∑xf ∑ f ∑ fx2 − ∑ ( fx)2


average = and stdev = .
∑f ∑ f (∑ f − 1)
In Excel these become

average =SUMPRODUCT(I2:I21,J2:J21)/SUM(J2:J21), and

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®

Table 9.2. Statistics from grouped data.

average 5.04000 error −0.12%


stdev 1.499967 error 1.70%

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

Chapter 10
Electrostatics

10.1 Coulomb’s law


A popular electrostatics undergraduate level experiment [1] involves two balls that
have been given equal charges. One is held on a rod while the other is attached to an
overhead point by a light wire and is free to move—see figure 10.1. The experimenter
moves the ball on the rod and observes the new position of the second ball. From the
mg
free-body diagram it is seen that Fe = L x2 and from Coulomb’s law we know that
1 1
Fe ∝ . Combining these we have x2 ∝ . The experimenter, therefore, makes
r2 (x2 + x1 )2
a plot with 1/(x2 + x1 )2 values on the abscissa and x2 values as the ordinate to
demonstrate a linear relationship.
(Worksheet: Coulomb in Electrostatics.xlsx.) The purpose of the notes that follow is
to generate some sample data so the instructor may more effectively talk about the
plotting process and checking for linearity. Part of the worksheet is shown in figure 10.2.
1) In A5:A25 enter the series 0, 0.1, 0.2,…, 2.0; in B5:B25 enter 1 in every cell.
2) In C5 enter formula =3/(A5+B5)^2 (the value 3 could be any other
number) and copy this down to C15.
3) Use Solver to make B5:B25 equal to C5:C25 by changing B5:B25.
Having x2 values that are exactly equal to the 1/(x2 + x1 )2 values will be
confusing. Also the x2 values are too precise.
4) In C5 modify the formula to =1/(A5+B5)^2 and copy this down to C15.
5) In D5 enter =ROUND(B5+(1-RAND())/10,2) and copy down to D25.
6) We now convert the formulas in D5:D25 into values placed in C5:C25. Copy
this range D5:D25, click on B5 and use Paste Special Values. Delete D4:D25.
We now have faux experimental data with built-in measurement errors.
7) Make a XY chart from B4:C25. Add a trendline to show the linearity. Use
Slope and INTERCEPT (or LINEST) to discover the slope and intercept.

doi:10.1088/978-1-627-05419-5ch10 10-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 10.1. Coulomb’s law experiment setup.

Figure 10.2. Coulomb’s law experiment.

10-2
Modelling Physics with Microsoft Excel®

10.2 Electrostatic potential


(Worksheet: Field in Electrostatics.xlsx.) Two particles, each bearing a positive
charge q, are fixed at points (0,1) and (0,−1), respectively1—see figure 10.3. Our task
is to locate the points on the x-axis having (i) the maximum electric field E and
(ii) field values of 1 that maximum. We will find approximate solutions graphically
2
and more precise values with Solver.
kq
The field at P resulting from the charge A has magnitude ∣ E AP ∣ = 2 and that from
r
B has the same magnitude. By symmetry, the vertical components of these two
2kq
fields cancel while the horizontal ones superimpose to give ∣ Ex ∣ = 2 cos(θ ) =
r
q x x
2k = 2kq . There is a similar field at point P′.
(x 2 + 1) (x 2 + 1) (x 2 + 1) 3/2

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.

Figure 10.3. Electrostatic potential.

1
This problem is adapted from problem 22–78 in [2].

10-3
Modelling Physics with Microsoft Excel®

Figure 10.4. Electrostatic potential worksheet.

Of course we could differentiate x


to show the maximum occurs at x = 1/√2
(x 2 + 1)3/2
or 0.707 107. However, to find the positions where E = 1 E max would require solving
2
a cubic equation.
Excel provides another method. On the worksheet the reader will see the values of
x for E max and for 1 E max found using Solver: 0.707 107 for the first, and 0.204 668
2
and 1.896 383 for the second.

10.3 Discrete form of Laplace equation


In chapter 4 we invoked the mean-value theorem to find the profile. Let us look at a
similar problem: we have a long rectangular tube, the sides of which are charged to
known voltages. We are tasked with finding the voltages at various points in a
typical cross-section of the tube.
∂ 2V ∂ 2V
The Laplace equation for two dimensions may be written as + = 0.
∂x 2 ∂y 2
Standard textbooks discuss how this may be discretized and how the mean-value
theory can be obtained.
(Worksheet: Laplace in Electrostatics.xlsx.) In this worksheet (figure 10.5) we use
the iterative calculation method discussed in the first part of chapter 4. Voltages of
100, 50, 50 and 0 were chosen for the four sides. A 5 × 5 mesh was constructed and
iterative calculations were enabled. To test if we have enabled the iterations and

10-4
Modelling Physics with Microsoft Excel®

Figure 10.5. Laplace equation in two dimensions.

Figure 10.6. Conditional formatting to display results.

performed sufficient calculations, in J5 we have the formula =IF(ABS(AVERAGE


(B5,C4,D5,C6)-C5)<0.000 000 01,“OK”,“Set Iteration”). A chart of
the results was produced—see the workbook to see how this was done.
(Worksheet: Laplace(2) in Electrostatics.xlsx.) Emboldened with success, we
decrease the mesh sizes and work with a 19 × 19 mesh. The final results are shown in
figure 10.6.

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

Modelling Physics with Microsoft Excel®


Bernard V Liengme

Chapter 11
Random events

11.1 Random walk and Brownian motion


In 1826 Robert Brown reported observing that tiny pollen particles suspended in
water could be seen under the microscope moving in a random manner. Einstein, in
1905, published a paper [1] entitled ‘On the motion of small particles suspended in a
liquid at rest, as required by the molecular-kinetic theory of heat’. Interestingly,
Einstein appears to claim [2, p 103] that he was not attempting to explain Brownian
motion. Notwithstanding this, his paper did explain the motion and, furthermore, in
the words of Max Born [2, p 106] ‘[did] more than any other work to convince
physicists of the reality of atoms and molecules’.
Our analysis will lack the mathematical rigor of Einstein, but will demonstrate
how to model random events in Excel with the RAND() function.
(Worksheet: Sheet1 in RandomWalk.xlsx.) Figure 11.1 shows our worksheet. The
particle is located at the coordinates in columns C and D, and its distance from the
origin is computed in column H. A random angle is generated in column F and this
is used in the next row to increment the particle’s coordinates. In rows 3 and 4 we
have the values and formulas listed in table 11.1.
The formulas in row 4 are copied down to row 123. Figure 11.2 displays charts
showing (i) the position of the particle in the first 20 moves, (ii) its position in 120
moves and (iii) the distance it has moved from the origin after each move. Pressing
the F9 key will cause all RAND() functions to generate new values, which in turn will
re-compute the x and y coordinates and the distance moved.
(Worksheet: Sheet2 in RandomWalk.xlsx.) If we are to make a more realistic
attempt at modeling Brownian motion we must reassess the assumption that every
move results in a unit displacement from it previous location. To this end we add a
new column (figure 11.3) which generates a random displacement with a normal
distribution about a mean of 1 and a standard deviation of 1.

doi:10.1088/978-1-627-05419-5ch11 11-1 ª Morgan & Claypool Publishers 2014


Modelling Physics with Microsoft Excel®

Figure 11.1. Brownian motion.

Table 11.1. Formulas for rows 3 and 4.

Cell Formula Cell Formula

A3 the value 0 A4 =A3+1


C3 the value 0 C4 =C3+COS(RADIANS(F3))
D3 the value 0 D4 =D3+SIN(RADIANS(F3))
F3 =RAND()*360 F4 =RAND()*360
H3 =SQRT(C3^2+D3^2) H4 =SQRT(C4^2+D4^2)

Table 11.2. Formulas for rows 3 and 4.

Cell Formula Cell Formula

A3 the value 0 A4 =A3+1


C3 the value 0 C4 =C3+G3*COS(RADIANS(F3))
D3 the value 0 D4 =D3+G3*SIN(RADIANS(F3))
F3 =RAND()*360 F4 =RAND()*360
G3 =ABS(NORMINV(RAND(),1,1)) G4 =ABS(NORMINV(RAND(),1,1))
H3 =SQRT(C4^2+D4^2) H4 =SQRT(C4^2+D4^2)

To ensure positive displacements we enclose this within an ABS function. The


step size is incorporated into the (x, y) values in columns C and D. The formulas are
listed in table 11.2.
Note: on Excel’s RAND() and RANDBETWEEN() functions, RAND() returns an
evenly distributed pseudo-random real number greater than or equal to 0 and
less than 1. A new random real number is returned every time the worksheet
is calculated. To generate a number in the range a–b use =RAND()*(b-a)+a.

11-2
Modelling Physics with Microsoft Excel®

Figure 11.2. Charting Brownian motion.

Figure 11.3. Brownian motion 2.

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®

Figure 11.4. Brownian motion after recalculation.

11.2 A random self-avoiding walk


Consider a polymer chain with N links confined to a square two-dimensional lattice.
Various papers report that if RN is the experimental end-to-end distance then
R N2 ≈ N 2υ with ν = 0.75. Macdonald states [3]:

The polymer chain is embedded in an initial state in the lattice. We usually


start with a straight chain. A monomer on the chain is selected at random and
an available direction at this local site is selected at random. The shorter
portion (to reduce computation) is moved to this new direction. We treat at
this instant the rest of the chain as a rigid structure and only consider the
rotation about the selected monomer. The new conformation is accepted if the
excluded volume criterion is satisfied—if not the old conformation is retained.
The process is continued by the selection of another monomer which now
becomes the pivot and the whole process is repeated. Conformations are
accepted after a preset number of attempts.

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®

Figure 11.5. Initial settings for the chain experiment.

Figure 11.6. The chain experiment in progress.

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®

time on an Intel Core I3 machine is about 15 s for N = 10 000 and 11 nodes.


The displayed result of 26.1523 compares well with the known exact value of
26.2425 given by MacDonald [3].
The user can expand the initial chain to have fewer or more nodes; everything
looks after itself other than the chart, whose axes’ limits will need changing. The
worksheet uses named ranges (see below). The ability to resize the chain with no
adverse consequences results from of the use dynamic named ranges—those defined
with the OFFSET function.

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.

Option Explicit Variables are declared outside


Option Base 1 of a subroutine to make them
Dim cdata As Variant, ctemp As Variant global i.e. available within all
Dim high, low, centre subroutines
Dim myCount, myLength, totalLength
Dim start_time, end_time

Sub MyChain() The main subroutine


Worksheets("Sheet1").Activate
Dim mymax, mymin, myN
start_time = Now()
myN = Range("MaxN")
myCount = 0
totalLength = 0
Dim sintheta, pivot, interate
cdata = Range("chain").Value
ctemp = cdata
high = UBound(cdata)
low = LBound(cdata)
centre = Round(high / 2 + 0.5)

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)

mymax = high - 1: mymin = low + 1


pivot = Int((mymax - mymin + 1) * Rnd + mymin)

Call moveChain(pivot, sintheta)


Call checkChain
'Range("N").Value = myCount
If (myCount Mod 100) = 0 Then Call ShowData
Loop
Call ShowData
end_time = Now()
Range("Running_time") = DateDiff("s", start_time, end_time)

End Sub

The next two subs could have


been included above but the
author likes to modularize code

Sub moveChain(pivot, sintheta)


ctemp = cdata
Dim k, xpivot, ypivot, upper, lower, temp
xpivot = cdata(pivot, 1)
ypivot = cdata(pivot, 2)
If pivot >= centre Then Note that the middle node
upper = high: lower = pivot remains in its original
Else position—we are not interested
upper = pivot: lower = 1 in translational motion
End If

For k = lower To upper


cdata(k, 1) = cdata(k, 1) - xpivot
cdata(k, 2) = cdata(k, 2) - ypivot

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

You might also like