A Model Equation Differential Equation - CAE Users

advertisement
3/8/2016
James P. Blanchard
Simulating Time Dependent Systems with Microsoft Excel
James (Jake) Blanchard
University of Wisconsin – Madison
blanchard@engr.wisc.edu
Introduction
This document demonstrates the use of Visual Basic for Applications
(VBA) macros to simulate time-dependent systems using Microsoft Excel. This
tool allows one to relatively easily study a wide variety of systems, thereby
permitting the creation of tools that allow students to explore the solutions to
these engineering problems without them having to understand the nature of the
equations or of the methods used to solve them. The user interface tools made
available with VBA allow one to enhance the tool and its usability.
The first portion addresses the solution of differential equations, while the
second portion deals with cellular automata. There is a section at the end that
gives a brief overview of the use of VBA.
A Model Equation Differential Equation
Our model differential equation is a first order, ordinary differential
equation, which can be written as
dy
 f (t , y )
dt
Our goal is to determine a solution for y as a function of time, given the function
f(t,y) and an initial value for y. Some sample equations are described at the end
of this document.
To solve an equation such as the one above, we divide time into discrete
time steps, with a step length given by dt, and then find a value for y at the end
of each step. In this document, I use the fourth-order Runge-Kutta scheme for
this. In the attached spreadsheet, the function is provided in a macro and the
initial value for y and the time step are provided in the worksheet that will
ultimately contain the solution.
Fourth Order Runge Kutta for First Order Ordinary Differential Equations
The fourth order Runge-Kutta scheme can be written as follows:
k1  h * f (t , y )
k
h
k 2  h * f (t  , y  1 )
2
2
k
h
k 3  h * f (t  , y  2 )
2
2
k 4  h * f (t  h, y  k 3 )
y (t  h)  y (t ) 
( k1  2 * ( k 2  k 3 )  k 4 )
6
1
3/8/2016
James P. Blanchard
In this scheme, h is the width of the time step. As this time step width decreases,
the accuracy of the solution increases. This algorithm, which takes a solution at
the beginning of a time step and determines the solution at the end of the step,
is easily implemented in a VBA macro. A sequence of these steps will then
provide a solution for y(t). This is implemented in a macro function called rk,
which has the following form:
Function rk(h, t, y)
k1 = h * f(t, y)
k2 = h * f(t + h / 2, y + k1 / 2)
k3 = h * f(t + h / 2, y + k2 / 2)
k4 = h * f(t + h, y + k3)
rk = y + (k1 + 2 * (k2 + k3) + k4) / 6
End Function
Function f(t, y)
r = [h10].Value
lambda = [h12].Value
F = r - lambda * y
End Function
This function is written to solve the differential equation
dN
 R  N
dt
A spreadsheet that solves the differential equation using this macro is provided
in the materials accompanying this workshop.
Note that to create a function such as this, you start up the built-in macro
editor by going to Tools/Macro/Visual Basic Editor. Then you can go to
Insert/Module and create a blank module, which is the object that contains
macros. You can then type or paste in the above commands, and then return to
the worksheet to call this function and generate a solution to the above equation.
Using the Macros
The enclosed spreadsheet provides several generic functions for solving
differential equations, along with several examples. To use one of these to solve
a new set of equations, you must simply provide the function or functions that
define the first derivative of the dependent variable and an initial condition. The
function is changed by editing the function in visual basic, while the initial
condition is changed from the worksheet.
To edit the Visual Basic macro, go to Tools/Macro/Visual Basic Editor to
start up the editor designed to edit VBA code. In the upper left you will see a list
of worksheets and a list of Modules. The VBA code is kept in the Modules and
will be saved with the worksheet. If the Module you would like to edit is not
already open, you can simply click on the Module name in the upper left window
2
3/8/2016
James P. Blanchard
to open it. Then you can make changes in the macro and return to the worksheet
to test your changes.
VBA is a very powerful language and I've not made an attempt to provide
detailed information about how to use it. If you would like to explore it further,
these books are excellent sources of information:


Microsoft Excel 2000 Power Programming with VBA, Walkenbach, J.,
1999. [ISBN: 0764532634]
Writing Excel Macros, Roman, S., O'Reilly & Associates, 1999. [ISBN:
1565925874]
There is also a brief discussion of the use of these tools at the end of this
document.
Examples
Filling a Tank with Water
Consider a tank that is filled with water from a faucet at the top and is
emptied from an orifice near the bottom (see figure below). The orifice is
designed such that the rate at which water leaves the tank is proportional to the
depth of the tank.
orifice
water level
h
The equation governing the height of the tank is
A
dh
 Qin  a 2 gh
dt
Where h is the height, A is the cross sectional area of the tank, Q in is the rate at
which water enters the tank, and a is a parameter characterizing the orifice. If a
is low, the loss rate is low and the tank will tend to overflow. If a is high, the loss
rate is high and the depth of the water will tend to drop.
3
3/8/2016
James P. Blanchard
Terminal Velocity
When a body falls in air, resistance (drag) reduces its velocity. This drag
force increases with velocity. If allowed to fall far enough, the body will reach a
terminal velocity, in which the drag force just balances the force due to gravity.
The velocity of a body falling in air is governed by the following equation:
dV
 mg  FD
dt
1
FD  C D  AV 2
2
m
where m is the body's mass (kg), V is the velocity (m/s), and the last term
represents the drag force for a particular mass. The drag force is assumed to be
described by the second equation, which depends on the drag coefficient (CD),
density (), cross-sectional area (A), and velocity. Over a fairly large velocity
range, the drag coefficient can be assumed to be ½. The terminal velocity can be
found by setting the derivative term to zero and solving for the velocity, but
solving the differential equation will also tell us how long it takes the body to
reach the terminal velocity.
Carbon Dating
One way to determine the age of an old artifact is through carbon dating.
This approach relies on the fact that all living things tend to contain one 14C atom
for every 1012 atoms of 12C. Once this organism dies, the 14C will begin to decay
away with a half-life of approximately 5730 years. Hence, one can determine the
age of this artifact by comparing its specific activity to that of living things. This is
examined in the spreadsheet accompanying this workshop.
Population Growth
The population of a particular squirrel species is governed by the following
differential equation:
dP
P 

 P 1 

dt
 100 
Determine the time dependence of P, if the initial population is 20.
Cellular Automata
Cellular Automata model physical systems by providing rules to govern
the time dependence of the state of a cell according to the state of other cells in
the vicinity. In some situations, one can develop systems that model very
complex behavior using just a few simple rules. An array of cells is typically
referred to as an automaton, and each cell is an automata. An automaton is
often a two-dimensional grid of automata, with a set of If-Then statements used
4
3/8/2016
James P. Blanchard
to define the behavior of an automata based on the state of the neighboring
automata.
One can envision using a spreadsheet to model such systems, employing
complex If statements into each cell. This can be difficult, as such formulas can
be quite complicated and a spreadsheet formula is not an ideal venue for such
equations. A less error-prone approach is to use the VBA macro language built
into Excel to develop the rules. This is the approach used here.
A Sample Automaton
As an example of such a system, we will consider a model for population
growth. This model, taken from http://classes.entom.wsu.edu/529/529Homework4.html,
uses the following rules to advance a population:




A cell value of 1 implies the cell is populated, while a 0 implies it is not
A populated cell surrounded by more than 5 populated cells will die
due to overcrowding
A populated cell surrounded by less than 2 populated cells will die due
to isolation
A populated cell with 2-5 populated neighbors will spawn children into
some of the neighboring unpopulated cells with a fixed probability that
any individual unpopulated cell will be populated
The Visual Basic Code used to simulate this model is as follows:
Sub population()
Const ncells As Integer = 16
Dim values(ncells, ncells) As Integer
Dim nuvalues(ncells, ncells) As Integer
birthfactor = [G1].Value
Cells(1, 2).Value = Cells(1, 2).Value + 1
For i = 1 To ncells
For j = 1 To ncells
values(i, j) = Cells(i + 2, j + 2)
Next
Next
If (Cells(1, 2).Value) = 2 Then
For i = 1 To ncells
For j = 1 To ncells
addup = addup + values(i, j)
Next
Next
Cells(1, 1) = addup
End If
For i = 2 To ncells - 1
For j = 2 To ncells - 1
If values(i, j) = 1 Then
c1 = values(i - 1, j - 1)
c2 = values(i, j - 1)
c3 = values(i + 1, j - 1)
c4 = values(i - 1, j)
c5 = values(i + 1, j)
c6 = values(i - 1, j + 1)
c7 = values(i, j + 1)
5
3/8/2016
James P. Blanchard
c8 = values(i + 1, j + 1)
neighborsum = c1+ c2+ c3+ c4+ c5+ c6+ c7+ c8
If (neighborsum > 5) Or (neighborsum < 2) Then
nuvalues(i, j) = 0
Else
nuvalues(i, j) = 1
If c1 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i - 1, j - 1) = 1
End If
End If
If c2 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i, j - 1) = 1
End If
End If
If c3 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i + 1, j - 1) = 1
End If
End If
If c4 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i - 1, j) = 1
End If
End If
If c5 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i + 1, j) = 1
End If
End If
If c6 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i - 1, j + 1) = 1
End If
End If
If c7 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i, j + 1) = 1
End If
End If
If c8 = 0 Then
If (Rnd < birthfactor) Then
nuvalues(i + 1, j + 1) = 1
End If
End If
End If
End If
Next
Next
For i = 1 To ncells
For j = 1 To ncells
Cells(i + 2, j + 2) = nuvalues(i, j)
Next
Next
addup = 0
For i = 1 To ncells
For j = 1 To ncells
addup = addup + nuvalues(i, j)
Next
Next
6
3/8/2016
James P. Blanchard
Cells(Cells(1, 2).Value, 1) = addup
End Sub
This code reads the states of each cell from the spreadsheet, updates the cells
according to the predetermined rules, and then writes the results back to the
sheet. There is a button on the sample worksheet to execute the macro and the
macro also keeps track of the total population as it goes along and writes that
back to the sheet.
Example
A second example of a cellular automaton is the fire simulation (taken
from (http://www.ecu.edu/si/cd/excel/tutorials/forestfire_model.html). In this case, an
individual cell can have any integer value between 0 and 3. A value of 3 implies
the cell is burning, a 2 implies burnt, a 1 implies re-grown, and a 0 implies
susceptible to fire. All cell values reduce by 1 from generation to generation,
except a cell with a value of 0. A cell with a value of 0 will remain at 0 unless
there is one or more neighbors which are burning. In that case, this cell takes on
a value of 3.
7
3/8/2016
James P. Blanchard
Using Visual Basic for Applications
Background
All Microsoft Office programs can be enhanced using the built-in macro language called
VBA. This is especially valuable for problem solving because it helps us to automate
various tasks that are difficult to carry out in a spreadsheet.
References
Liengme discusses the use of VBA in Chapter 8. For more detailed references, you
might want to take a look at the following books:
Microsoft Excel 2000 Formulas, Walkenbach , J., IDG Books Worldwide, 2000. [ISBN:
0764546090]
Microsoft Excel 2000 Power Programming with VBA, Walkenbach, J., 1999. [ISBN:
0764532634]
Writing Excel Macros, Roman, S., O'Reilly & Associates, 1999. [ISBN: 1565925874]
Recording a Macro
The easiest way to create a macro in Excel is to use the recorder. For example, we
could create a macro which will format a cell to display a number as currency. To do so,
carry out the following steps:
1. Put any number into cell A1 of a fresh sheet. Click in cell A1 to select it.
2. Start recording the macro by clicking Tools/Macros/Record New Macro. This will
open up a small window with a Stop Recording button. We'll need that later.
3. In the resulting dialog box, give the macro a name; I used "formatcurrency" (see
figure below)
4. Give the macro a shortcut key; I used Ctrl-Shift-C
5. Now format the cell by going to Format/Cells and click on the Number tab on the
dialog box. Click on Currency in the list of formats.
6. Now stop recording by clicking the stop button in the Stop Recording window that
popped up when you started recording.
The dialog box for naming the Macro looks like this:
8
3/8/2016
James P. Blanchard
To use the macro, you can put a number in another cell, highlight that cell, and then
press Ctrl-Shift-C to format the number in the cell. Then you can enter a series of
numbers, highlight them all, and press Ctrl-Shift-C to format all of them. You can begin
to imagine how macros such as this might save time.
We can look at the macro this recording process produced. Click on
Tools/Macros/Visual Basic Editor. This opens up the Editor in a separate window. Mine
looks like this:
The left window shows the Book1 spreadsheet with Objects and Modules. The Visual
Basic macros go into the modules. On the right is the macro that we recorded. It takes
the selected cells and changes the NumberFormat to "$#,##0.00". If you want to remove
the numbers after the decimal point, you can change this to "$#,##0" and then rerun the
macro back in the spreadsheet.
For most problem solving applications, recording of macros is not feasible. In this case,
we need to be able to write our own macro.
9
3/8/2016
James P. Blanchard
Writing a User-Defined Function
To create our own function, we go to the Visual Basic Editor and click on Insert/Module.
This will bring up a blank module window within the editor. Then you can type the
following in the module:
Function f(x)
f = Sin(2 * x) + Sin(2.1 * x)
End Function
This creates a function f(x) which takes an argument (x) and returns the desired
function. You can then return to the spreadsheet and call the function f(x) just as if it
was built into Excel. So you can go to cell A1 (or any other cell) in any worksheet and
type f(3) and it will return sin(6)+sin(6.3). The result should be -0.2626.
Functions Available in Visual Basic for Applications for Excel
The following functions can be used in a VBA module:




Trig: Sin, Cos, Tan, Atn (Atn is the inverse tangent function. All other inverse trig
functions must be derived from Atn. Some guidance is provided in the Visual
Basic help files.)
Rounding: Int and Fix
Logarithms: Log (this is natural log), Exp
Other: Sqr (square root), Rnd (random number between 0 and 1), Abs (absolute
value)
Flow Control in VBA
VBA provides several statements for doing flow control. A couple of the more common
are "If" statements and "For" loops. I'll briefly explain each of these below. The general
form of the "If" statement is:
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ...
[Else
[elsestatements]]
End If
As an example, suppose we wanted to a function which is equal to 1 for 0<x<2 and 0
elsewhere. We could do so with the following statements:
Function z(x)
If x > 2 Then
z = 0
ElseIf x < 0 Then
z = 0
Else
z = 1
End If
End Function
10
3/8/2016
James P. Blanchard
"For" loops are used to repeat a statement a fixed number of times. The general form of
the statement is:
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]
As an example, suppose we wanted to sum up the first N integers for a given value of N.
To do so, we could use the following function:
Function sumup(N)
total = 0
For i = 1 To N
total = total + i
Next
sumup = total
End Function
An Example
To demonstrate a typical application using VBA and Excel, I will put together a macro to
calculate the temperatures in a quenched cylinder. If an infinite slab, initially at
temperature To, has its surface temperature suddenly changed to Ts, the heat removed
as a function of time is given by:

1 (1) n 
(n )2 Fo
Q  4Qi  
1e
2

n1  (n )


where Qi is the initial heat content of the slab and Fo is the Fourier modulus, given by:
Fo 

L2
Here  is the thermal diffusivity of the slab,  is the time, and L is the slab width. The
following macro carries out this calculation, truncating the series to 30 terms.
Function fracheatlost(t)
'calculate fraction of heat lost from infinite slab
alpha = 0.02 ' ft^2/hr
slablength = 10 / 12 ' feet
numterms = 30
cumsum = 0
fo = alpha * t / slablength ^ 2
Pi = 4 * Atn(1) ' pi isn't built-in, so calculate it
For N = 1 To numterms
cumsum = cumsum + (1 - (-1) ^ N) / (N * Pi) ^ 2 * (1 - Exp(-(N * Pi) ^ 2 *
fo))
Next
fracheatlost = 4 * cumsum
End Function
The single quote denotes that a comment follows. Note that more terms are needed for
11
3/8/2016
James P. Blanchard
shorter times and the result from this macro is not accurate for times less than about 0.2
hours. Another way to carry this out is to read the input variables from the spreadsheet.
One way to do this is as follows
Function fracheatlostagain(t)
'calculate fraction of heat lost from infinite slab
alpha = Range("B2")
slablength = Range("B3")
numterms = Range("B4")
cumsum = 0
fo = alpha * t / slablength ^ 2
Pi = 4 * Atn(1) ' pi isn't builtin, so calculate it
For N = 1 To numterms
cumsum = cumsum + (1 - (-1) ^ N) / (N * Pi) ^ 2 * (1 - Exp(-(N * Pi)
^ 2 * fo))
Next
fracheatlostagain = 4 * cumsum
End Function
In this case, the value of alpha is set in the macro by taking the value from cell B2 in the
active sheet. To use this macro, just set the constants in the sheet and then call the
function from within the cells.
12
Download