












































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













































































0.2 Resources
The concepts and methods of technical computing are summarized in the excellent book of Chapra and Canale: Numerical Methods for Engineers (CC). In order to make efficient use of our time, we request you to read the material before the lecture. Any similar book can be used, however. The Visual Basic for Applications (Excel) program development environment will be available in the lab. Whenever you are asked to solve a problem by computer, we request an Excel Workbook with Visual Basic source code and results. Excel and VBA for Excel has a vast literature. We will give you the opportunity to experiment with many of the numerical methods using a Living Textbook, developed particularly for this course. To make full use of the Living Textbook you will need a software system called Mathematica. This course, however, does not require you to learn how to program in Mathematica. In fact, to run any portion of the Living Textbook you will need minimum knowledge which can be acquired in 5 minutes. Many of the specific petroleum engineering problems also will be provided in the form of Living Textbook. You may experiment with them and may use the results for checking your Visual Basic for Applications (VBA) program results.
Basic References
S.C. Chapra and R. P. Canale : Numerical Methods for Engineers, McGraw Hill, any edition, any year (or any similar title)
Either of the following (or any similar title) a) Larsen: Engineering with Excel, Prentice Hall, 2002 b) Liengme: A guide to Microsoft Excel 2002 for scientists and engineers, Butterworth Heinemann, 2002 c) Bloch : Excel for Engineers and Scientists, 2002
All of your Petroleum Engineering Books
Special thanks go to L. Piper, B. Maggard, R. Archer, R. Wattenbarger.
0.3 Course structure
(a) Engineering problem solving approaches, software tools (b) Excel (c) VBA (d) Structured and Modular Programming
(a) Taylor polynomial, Numerical errors, Error propagation (b) Iteration, Convergence, Order, Stability, Sensitivity (c) Classification of problems and methods
(a) Roots of equations and extrema of functions Bisection; False position; Newton; golden ratio search (b) Numerical differentiation and integration Finite difference; Trapezoid rule; Simpson’s rule (c) Interpolation, Smoothing, Curve fit, Least squares (d) Numerical solution of ordinary differential equations
(a) Matrices, vectors (b) System of linear equations (c) Gauss, Gauss-Jordan, LU decomposition Special cases, Iterative methods (d) Multivariable nonlinear equations: Newton-Raphson (e) Multivariable extrema: Nelder-Mead simplex, Fully nonlinear least squares
(a) Classification and Numerical Solution of PDEs (b) Transient solution of the diffusivity equation (c) Reservoir simulation
(a) Spectral methods (b) Laplace transform inversion
To create a new workbook: On the File menu, click New, and then click Blank Workbook on the New Workbook task pane.
To save a workbook: On the File menu, click Save As. In the File name box, type a new name for the workbook. In the Save as type list, click a file format (if you want other than .xls) (In general, it is useful to click the right mouse button. Most of the time it will offer a menu item you really want.)
A Microsoft Excel workbook is a file that contains one or more worksheets, which you can use to organize various kinds of related information. You can enter and edit data on several worksheets simultaneously and perform calculations based on data from more than one worksheet. When you create a chart, you can place the chart on the same worksheet as its related data or on a separate chart sheet. To view and scroll independently in different parts of a worksheet, you can split a worksheet horizontally and vertically into separate panes. Splitting a worksheet into panes allows you to view different parts of the same worksheet side by side and is useful, for example, when you want to paste data between different areas of a large worksheet. To see how it will look like in print: On the View menu, click Page Break Preview. Before you do any work, make sure that you macros are allowed (security level is low) and you can save an excel spreadsheet to your own disk.
The difference between relative and absolute references is the key concept to understand:
Relative references A relative cell reference in a formula, such as A1, is based on the relative position of the cell that contains the formula and the cell the reference refers to. If the position of the cell that contains the formula changes, the reference is changed. If you copy the formula across rows or down columns, the reference automatically adjusts. By default, new formulas use relative references. For example, if you copy a relative reference in cell B2 to cell B3, it automatically adjusts from =A1 to =A2.
Absolute references An absolute cell reference in a formula, such as $A$1, always refer to a cell in a specific location. If the position of the cell that contains the formula changes, the absolute reference remains the same. If you copy the formula across rows or down columns, the absolute reference does not adjust. By default, new formulas use relative references, and you need to switch them to absolute references. For example, if you copy a absolute reference in cell B2 to cell B3, it stays the same in both cells $A$1.
1.4 Graphing with Excel
Import a text file Click the cell where you want to put the data from the text file. To ensure that the external data does not replace existing data, make sure that the worksheet has no data below or to the right of the cell you click. On the Data menu, point to Import External Data, and then click Import Data. In the Files of type box, click Text Files. Check out also: On the Data menu: Text to Columns.
Creating an XY (Scatter) Plot You can create a chart on its own sheet or as an embedded object on a worksheet. You can also publish a chart on a Web page. To create a chart, you must first enter the data for the chart on the worksheet. Arrange your data in columns, with x values in the first column and corresponding y values and/or bubble size values in adjacent columns. Then select that data and use the Chart Wizard to step through the process of choosing the chart type XY and the various chart options, or use the Chart toolbar to create a basic chart that you can format later. Best-fit equations may be calculated for chart data via the Add Trendline dialog. Trendline equations are displayed by checking the correct box under the Options tab Errors bars can be added to a chart by left clicking on a data series, and accessing the Format Data Series dialog box
Editing an Existing Graph Check out.
Creating Graphs with Multiple Curves Check out.
More graphs types Check out.
1.5 Numerical methods inside Excel
Goal Seek The Goal Seek dialog box can be used to solve for roots of a single equation. An initial guess is needed. Goal Seek performs calculations which improve the solution accuracy.
(c) String manipulation (d) File system
(a) Data management (b) Graphics (c) Solver (for optimization and root finding)
(a) Dialog and input boxes (b) Custom user forms with spinners,checkboxes, etc. (c) Custom menus and toolbars
Example: VBA011 program (After Hahn): If a stone is thrown vertically upward with an initial speed u, its vertical displacement s after a time t has elapsed is given by a simple formula. In this formula, g is the acceleration due to gravity. Air resistance has been ignored. We would like to compute the value of s, given u and t. Note that we are not concerned here with how to derive the formula, rather we want to compute its value. The logical preparation of this program is as follows:
This plan may seem trivial to you, and a waste of time writing down. Yet you would be surprised how many beginners, preferring to rush straight to the computer, try to program step 2 before step 1. It is well worth developing the mental discipline of planning your program first-if pen and paper turns you off why not use your word processor? You could even enter the plan as comment lines in the program.
Option Explicit Const g As Double = 9.81 ’ gravitational acceleration, m/s^
Sub VBA011() ’vertical motion under gravity Dim s As Double ’ vertical displacement, m Dim t As Double ’ time, s Dim u As Double ’ initial velocity, m/s
u = 30 t = 6 s = u * t - (g / 2) * t ^ 2 MsgBox "s = " & CStr(s) &" meters." ’ s is converted to a string End Sub
To make this program run do the following:
Some remarks:
Built-in (or intrinsic) functions Visual Basic has many built-in functions. You will often need the math functions: Abs, Atn, Cos, Exp, Fix, Int, Rnd, Sgn, Sin, Sqr, Tan. Log is natural-log. If you wish ten-based logarithm, use Log(x)/Log(10).
if you wish to declare both as integer.
Numerics VBA makes a clear distinction between integer and real. Integers are used for counting things. Real numbers include a fractional part. Real numbers stored as integers are rounded to the nearest integer.
Dim n As Integer, m As Double n = 4/3 !result is 1 n = 5/3 !result is 2 n = 7/2 !result is 2 n = 5/2 !result is 4 m = 5/2 !result is 2.
You should be aware of rules regarding priorities. For instance a frequent error is to write
z = pv/RT
instead of the correct:
z = pv/(RT)
Strings To convert any other value to a string, use the Cstr intrinsic function.
Objects,input and output The structure ”With/End With” and the ”operator” point can be understood if you are familiar with the concept of object. ”ThisWorkbook” is a hierarchical object. It has several Workseets (a whole collection of them). One of them is called ”Sheet2”. The following example shows how to read a number into variable ”a” from cell ”A4” of Sheet2:
With ThisWorkbook.Worksheets("Sheet2") a =.Cells(1, 4) End With
This will output date and time into cells ”A4” and ”A5” of ”Sheet2”:
Sub VBA014() Dim d As String, t As String d = Date() ’ Intrinsic function t = Time() ’ Intrinsic function ’ Display the result With ThisWorkbook.Worksheets("Sheet2") .Cells(1, 4)= d .Cells(1, 5)= t End With End Sub
(Objects have properties and methods associated with them. For instance, when you are formatting a cell, you change some of its properties using some methods available.)
Advanced topics: Variable scope, lifetime, visibility The following key words are important: Static, Public, Private. The scope of a variable is from where it can be reached/altered. Variables declared in a procedure can be used only within the procedure (local variable for the procedure).
Variables declared on the module level can be used in the entire modul in any of the procedures within the module (global variable for the module). Static variables keep their value between two occasions of entering into their scope. In other words, their lifetime is not limited to one call. In general, a procedure-level variable looses its value between two calls, unless it is declared Static. Both module-level variables and all procedures are Public, by default, meaning that they are visible even from other modules (or even other applications.) You can make them Private, and then they are visible only within the module. We will often use module level variables (globals) to simplify engineering problem solving, when some data are needed in various parts of the program.
Advanced topics: Argument passing by Value or by Reference All arguments are passed to procedures by reference, unless you specify otherwise. This is efficient because all arguments passed by reference take the same amount of time to pass and the same amount of space (4 bytes) within a procedure regardless of the argument’s data type. (You can pass an argument by value if you include the ByVal keyword in the pro- cedure’s declaration. Arguments passed by value consume from 2 16 bytes within the procedure, depending on the argument’s data type. Larger data types take slightly longer to pass by value than smaller ones.)
Errors, Debugging and Testing Compilation errors are errors in syntax and construc- tion, like spelling mistakes, that are picked up by the compiler during compilation, the process whereby your program is translated into machine code. They are the most fre- quent type of error. The compiler prints messages, which may or may not be helpful, when it encounters such an error. Generally, there are three sorts of compiler errors:
g = 9,81 ’ comma instead of decimal point x = 1 + (2 * 3 ’ unpaired parentheses .Cell(2,1)=5 ’ Wrong function name: Cell instead of Cells If (a=b) ’ Missing then x= Else x= End If
If a program compiles successfully, it will run. Errors occurring at this stage are called run-time errors, and are invariably fatal, i.e. the program ”crashes”. An error message, such as
Example Let in your Excel workbook, ”Sheet3” contain the following: Cells A1 and B should contain the X and Y coordinates of a point. Cells A2 and B2 should contain the X and Y coordinates of a second point. This program will read the coordinates of the two points and calculate the slope and intercept of the unique straight line defined by the two points, and output the results in a message box. These two subroutines should be contained in a brand new module within your VBA project. Because the My Line subroutine has arguments, it cannot be executed directly, like the previously discussed subroutines, by using the VBA Run menu.
Option Explicit Private Intercept As Double
Sub VBA015() Dim X1 As Double, X2 As Double, Y1 As Double, Y2 As Double Dim Slope As Double ’ Get the two points from the worksheet, "Sheet3": With ThisWorkbook.Worksheets("Sheet3") X1 = .Cells(1, 1) Y1 = .Cells(1, 2) X2 = .Cells(2, 1) Y2 = .Cells(2, 2) End With ’ Calculate the Slope and Intercept Call My_Line(X1, Y1, X2, Y2, Slope)
’ Display the result With ThisWorkbook.Worksheets("Sheet3") .Cells(3, 1)=" Slope:" .Cells(3, 2)= Slope .Cells(4, 1)= "Intercept:" .Cells(4, 2)= Intercept End With End Sub
’A subroutine used inside:
Sub My_Line(x As Double,y As Double,xx As Double,yy As Double,m As Double) m = (yy - y) / (xx - x) Intercept = y - m * x End Sub
Note: Watch for scope of the various variables! Intercept is a module level variable, but Slope is not. Intercept cannot be seen from other modules.
The If/Then/Else Decision Structure Example (after Hahn) Most banks offer differential interest rates-more for the rich, less for the poor. (The Else part may be missing and you may create more complex structure with Else If.)
If balance < 3000 Then apr = 0. Else apr = 0. End If
Loops: the heart of programming math
Countable: Do the block for i = 1, then i = 2 , etc.:
For i = 1 To 10 "block..." Next i
Count down: Do it for j = 100, then j = 90 etc.:
For i = 100 To 50 Step - block Next i
Forever: Loop forever unless ”If” stops it:
Do If "logical_expression..." Then Exit Do "block..." Loop
Condition controlled: Do while logical expression is true:
While "logical_expression..." "block..." Wend
”Select Case” structure makes your code readable Use the Select Case statement as an alternative to using ElseIf in If...Then...Else statements when comparing one expres- sion to several different values. While If...Then...Else statements can evaluate a different expression for each ElseIf statement, the Select Case statement evaluates an expression only once, at the top of the control structure.
Select Case performance Case 1 bonus = salary * 0. Case 2, 3 bonus = salary * 0. Case Is > 3 bonus = 100 Case Else bonus = 0 End Select
Arrays Arrays are declared the same way as other variables, using the Dim, Static, Private, or Public statements. The difference between scalar variables (those that aren’t arrays) and array variables is that you generally must specify the size of the array. An array whose size is specified is a fixed-size array. An array whose size can be changed while a program is running is a dynamic array. Whether an array is indexed from 0 or 1 depends on the setting of the Option Base statement. If Option Base 1 is not specified, all array indexes begin at zero.
Declaring a fixed array In the following line of code, a fixed-size array is declared as an Integer array having 10 rows and 10 columns: