This Week. Trapezoidal Rule, theory. Warmup Example: Numeric Integration. Trapezoidal Rule, pseudocode. Trapezoidal Rule, implementation

Similar documents
ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing

ENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration

More Complicated Recursion CMPSC 122

Ms Excel Vba Continue Loop Through Range Of

References. Iteration For. Iteration (Repetition) Iteration While. For loop examples

Solutions to Problem 1 of Homework 3 (10 (+6) Points)

Data. Selecting Data. Sorting Data

Excel. Spreadsheet functions

How to Open Excel. Introduction to Excel TIP: Right click Excel on list and select PIN to Start Menu. When you open Excel, a new worksheet opens

Table of Contents. Tip 1: Page setup 3. Tip 2: Printing different ranges in a spreadsheet 5. Tip 3: Ensuring that a long formula is displayed 6

Adjacent sides are next to each other and are joined by a common vertex.

APCS-AB: Java. Recursion in Java December 12, week14 1

2.3 Recursion 7/21/2014 5:12:34 PM

Name: Tutor s

ENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder. Examples

Introduction to Microsoft Excel

UNIT 15 Polygons Lesson Plan 1 Angles

Using Word & Excel to Label and Calculate Catchment Areas and Rainfall Income

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Angle, symmetry and transformation

6.001 Notes: Section 4.1

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

Using Flash Animation Basics

CS 112 Introduction to Programming

COMPUTING AND DATA ANALYSIS WITH EXCEL. Numerical integration techniques

ADD AND NAME WORKSHEETS

Working with Excel CHAPTER 1

Ms Excel Vba Continue Loop Through Columns Range

Earthwork 3D for Dummies Doing a digitized dirt takeoff calculation the swift and easy way

Working with Excel involves two basic tasks: building a spreadsheet and then manipulating the

Using Microsoft Excel

Separate Text Across Cells The Convert Text to Columns Wizard can help you to divide the text into columns separated with specific symbols.

Year 6 Summer Term Week 1 to 2 Geometry: Properties of Shapes

Unit 5: Recursive Thinking

ENGG1811 Computing for Engineers Chapra (Part 2 of ENGG1811 Text) Topic 10 (chapter 3) Macro Recorder. Examples

9. a. 11. A = 30 cm 2, P = 30 cm. 12. A = 29 cm 2, P = 13. A = 72 in. 2, P = 35 in.

Overview. What is recursion? When one function calls itself directly or indirectly.

Year. Small Steps Guidance and Examples. Block 1 Properties of Shapes. Released March 2018

You must bring your ID to the exam.

ENGG1811 Computing for Engineers Week 6 Iteration; Sequential Algorithms; Processing Cells

Name: Pythagorean theorem February 4, 2013

Computer Graphics Fundamentals. Jon Macey

Microsoft Excel XP. Intermediate

Using Microsoft Word. Tables

Rotated earth or when your fantasy world goes up side down

SPH3U1 Lesson 05 Kinematics

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions

GCSE-AS Mathematics Bridging Course. Chellaston School. Dr P. Leary (KS5 Coordinator) Monday Objectives. The Equation of a Line.

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Microsoft Excel 2013: Part 3 More on Formatting Cells And Worksheet Basics. To apply number formatting:

Intermediate Math Circles Wednesday, February 8, 2017 Graph Theory I

Unit 1, Lesson 1: Moving in the Plane

References. Parameters revisited. Reference Parameters. Example: Swapping values. Named Arguments

PRACTICAL GEOMETRY SYMMETRY AND VISUALISING SOLID SHAPES

Chapter 2 Assignment (due Thursday, April 19)

n! = 1 * 2 * 3 * 4 * * (n-1) * n

Excel Tools Features... 1 Comments... 2 List Comments Formatting... 3 Center Across... 3 Hide Blank Rows... 3 Lists... 3 Sheet Links...

COMP1000 / Spreadsheets Week 2 Review

References. Arrays. Default array bounds. Array example. Array usage. Shepherd, pp (Arrays) Shepherd, Chapters 12, 13

Workbooks (File) and Worksheet Handling

Civil Engineering Computation

References. Iteration For. Iteration (Repetition) Iteration While. For loop examples

INFORMATION FOR PARENTS AND CARERS TARGETS IN MATHEMATICS

Excel 2007 New Features Table of Contents

6/14/2010. VBA program units: Subroutines and Functions. Functions: Examples: Examples:

Using Microsoft Excel

Unit 8 Geometry I-1. Teacher s Guide for Workbook 8.1 COPYRIGHT 2010 JUMP MATH: NOT TO BE COPIED

Section T Similar and congruent shapes

SPH3U1 Lesson 09 Kinematics

(Refer Slide Time: 00:51)

Review Ch. 15 Spreadsheet and Worksheet Basics. 2010, 2006 South-Western, Cengage Learning

Spreadsheet Warm Up for SSAC Geology of National Parks Modules, 2: Elementary Spreadsheet Manipulations and Graphing Tasks

Math 124 Final Examination Autumn Turn off all cell phones, pagers, radios, mp3 players, and other similar devices.

Formulas Learn how to use Excel to do the math for you by typing formulas into cells.

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

What we will learn in Introduction to Excel. How to Open Excel. Introduction to Excel 2010 Lodi Memorial Library NJ Developed by Barb Hauck-Mah

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

26 Feb Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor

A Tutorial for Excel 2002 for Windows

1. CONVEX POLYGONS. Definition. A shape D in the plane is convex if every line drawn between two points in D is entirely inside D.

Stage 1 Intermediate Revision Sheet

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

2.3 Recursion 7/23/2015 3:06:35 PM

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents

Microsoft Excel 2010 Training. Excel 2010 Basics

CHAPTER 4: MICROSOFT OFFICE: EXCEL 2010

Haskell Review COMP360

Recursive Definitions

Budget Exercise for Intermediate Excel

Chapter 13. Creating Business Diagrams with SmartArt. Creating SmartArt Diagrams

COURSE CONTENT Excel with VBA Training

References. Parameters revisited. Reference Parameters. Example: Swapping values. Named Arguments

Teach Yourself Microsoft Office Excel Topic 17: Revision, Importing and Grouping Data

Excel 2010 Foundation. Excel 2010 Foundation SAMPLE

(Refer Slide Time: 00:02:00)

Intermediate Excel 2003

Let a line l and a point P not lying on it be given. By using properties of a transversal and parallel lines, a line which passes through the point P

Exploring extreme weather with Excel - The basics

Transcription:

This Week ENGG8 Computing for Engineers Week 9 Recursion, External Application Interfacing Monday: numeric integration example, then first part of the material Wednesday 9am: rest of the new material Wednesday pm: more worked examples, see slides 3-5 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide Warmup Example: Numeric Integration Numerical integration approximates the solution to a definite integral that may not have a closed form by using a series of shapes to model the area under the curve Simplest of these is the Trapezoidal Rule, which uses thin vertical slices with a straight line at the top (forming adjacent trapeziums) a f(x) b Integral of f(x) from a to b is approximated by the sum of the areas inside the red trapeziums ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 3 Trapezoidal Rule, theory References: Wikipedia, many other web refs Animation:http://www.ecs.fullerton.edu/~mathews/a00/Ani mations/quadrature/trapezoidal/trapezoidalaa.html After doing the maths for n equally spaced panels, the formula reduces to b a δ ( f ( x ) + f ( x ) + f ( x ) + K+ f ( x ) f ( x )) f ( x) dx n + Panel width b a δ = n 0 n Twice the middle values where xi = a + i( b a) / n = a + i *δ End-points counted once only ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 4 Trapezoidal Rule, pseudocode Trapezoidal Rule, implementation We can easily convert this to pseudocode: set sum to f (a) + f (b) set delta to the panel width For p = To add to sum Next p area = Function TrapArea(a As Double, b As Double, _ n as integer) As Double Limitations: for this quick example, we will represent the function to be integrated as a VBA function called directly from TrapArea. It is possible to specify it as a formula on the sheet, which is easier for end users (and was done in an assignment in previous years) ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 5 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 6

References Recursion is covered quite nicely at http://www.cs.princeton.edu/introcs/3recursion/ not quite so well in Chapra Section.4 Recursion Recursion Sometimes a solution to a problem can be expressed naturally in terms of one or more simpler versions of the same solution. For example, the factorial definition is just n! = n ( n )!, n! =, if n > 0 if n = 0 This is called a recursive definition, and can be implemented directly in most programming languages Recursion depends strongly on correctly identifying the base case, where no further subdivision occurs. ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 7 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 8 Recursive Factorial Recursion is implemented through functions or subprograms calling themselves rather than another procedure Works provided the base case is handled and there are sufficient resources to sustain the calculation Function fact(n As Integer) As Long If n = 0 Then fact = Else fact = n * fact(n-) End Function Tracing Factorial Trace the calculation as with other procedure calls fact(5) = 5 * fact(4) fact(4) = 4 * fact(3) fact(3) = 3 * fact() fact() = * fact() fact() = * fact(0) fact(0) = fact() = * = fact() = * = fact(3) = 3 * = 6 fact(4) = 4 * 6 = 4 fact(5) = 5 * 4 = 0 Each function waits for the recursive call to return Each function uses the value from the recursive call to calculate and return its factorial ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 9 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 0 Tail Recursion The Factorial function is an example of what s called tail recursion, where each call results in either no recursion (the base case), or one recursive call in an expression Tail recursion produces a sequence, called a stack of pending procedure calls Tail recursion can always be replaced by iteration, which generally consumes less resources Naughty Recursion Recursion often gets a bad name because implementing some algorithms directly produces horribly inefficient code that reevaluates things over and over Classic case is the Fibonacci sequence*: Function BadFib(n As Integer) As Long If n <= Then BadFib = Else BadFib = BadFib(n-) + BadFib(n-) End Function * Regrettably, this is the solution to Chapra s misguided exercise 6, page 47 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide

tree has n levels Why BadFib is Bad Tracing calls on BadFib produces a tree rather than a simple stack of calls: is evaluated three times independently F(4) F(5) F(6) F(4) Recursion in Nature Some things in nature contain elements that are smaller copies of themselves (this is called self-similarity). The branching patterns of creeks and rivers, ferns, cloud patterns and blood vessels are all examples. Anne Burns (Long Island University) has a nice paper on the web (ref below) describing general techniques for creating images such as this one. Nothing in the picture is real. http://www.mi.sanu.ac.yu/vismath/bridges005/burns/index.html ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 3 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 4 Recursive Drawings We can do a tiny bit of this with the simple drawing tools available Draw a simple figure, then several smaller copies positioned relative to the larger one Copies are drawn recursively Recursion stops when the elements get small enough that the detail can t be seen Can t (easily) convert to iteration unless only one copy (e.g., picture of A- series paper sizes) General approach: Recursive Drawing Procedure Sub DrawThing(x As Single, y As Single, size As Single) If size < MIN_SIZE Then Exit Sub draw figure at position (x, y) ' calculate position of first copy x = : y = DrawThing(x, y, size*scale_factor) ' same for other copies DrawThing(x, y, size*scale_factor) End Sub Constant describing the smallest effective size Constant describing the reduction in size for each copy Source: Wikipedia ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 5 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 6 H-Trees The following is from the Princeton reference. Recursive graphics. Simple recursive drawing schemes can lead to pictures that are remarkably intricate. For example, an H-tree of order n is defined as follows: The base case is do nothing for n = 0. The reduction step is to draw, within the unit square three lines in the shape of the letter H [then] four H-trees of order n, one connected to each tip of the H with the additional provisos that the H-trees of order n are centered in the four quadrants of the square, halved in size. Question: What size will the entire picture be compared to the first H? (This is related to Zeno s Paradox about Achilles and the Tortoise) H-Trees Apart from drawing a canvas, the algorithm for drawing an H-Tree centred on (x,y) is just (x+hsize,y HTree(x,y,size) :- If size < MIN_SIZE Then Exit Sub (x,y) hsize = size/ ' half-size (x+hsize,y-hsize) hsize) Draw horizontal line through (x,y) of length size Draw vertical lines through (x-hsize,y) and (x+hsize,y) HTree x-hsize, y+hsize, hsize ' bottom left HTree x-hsize, y-hsize, hsize ' top left HTree x+hsize, y-hsize, hsize ' top right HTree x+hsize, y+hsize, hsize ' bottom right Use a separate subprogram to draw the lines, so you can apply the attributes consistently and once only size hsize ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 7 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 8 3

H-Tree Demo See the demo workbook. To make it more useful as a learning tool, the following have been added a ClearDrawing subroutine a DrawCanvas subroutine (shape reference saved) a depth parameter, indicating how many calls are active colours, derived from the depth a visible stack, showing the depth in boxes timings, to demonstrate inefficiencies in VBA s collections Most important parts are the subprograms DrawHTree, HTree itself and DrawLine Office Interfacing All MS Office applications can start and interact with any other Office app For example, Excel can start Word and transfer data from a sheet to a table Word can start Outlook and send emails (if an email server is available) Excel can obtain data from an Access database (though this requires a lot of fiddling around) Depending on your processor, the picture will take a couple of minutes to draw, and the drawing rate will slow down as each line is added to the shape collection. ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 9 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 0 Example: Creating a Word Doc Object Reference Settings ' Example adapted from Shepherd, Excel VBA Sub Test_Word() Dim objwordapp As Word.Application ' reference to Word (the app) Dim objworddoc As Word.Document ' ref to a newly created doc Set objwordapp = CreateObject("Word.Application") Set objworddoc = objwordapp.documents.add With objworddoc.sections().range.text = "My new Word Document".SaveAs "c:\mytest.doc" ' must use full pathname.close End With ' These are required to make sure MS Word shuts down completely Set objworddoc = Nothing Set objwordapp = Nothing End Sub Unfortunately this fails to satisfy the compiler. The error points to Word.Application Select Tools References on the VBE menu, scroll to Microsoft Word * Object Library and check. Press OK. * or largest value: 0=Office00, =Office003, =Office007 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide This is the end of the new VBA material (all together now, a big groan of disappointment) Some short worked examples of the kind that could be set for the final exam will follow. A bearing is an angle measured clockwise from North Write a VBA subprogram that candy-stripes the active worksheet. Candy-striping fills the background of every second row with a faint grey colour. Stop with the first empty cell in column A. Use the macro recorder to gather information about colouring rows, then work on the loop to apply the fills. A back bearing is the bearing that is exactly opposite a given bearing. Bearings lie between 0 and 360 degrees. For example, if I'm sighting a landmark at that has a compass bearing of 0 degrees (slightly South of East), the back bearing is 90 degrees (slightly North of West). The back bearing is the bearing from the landmark back to me. Write a VBA function BackBearing that returns the back bearing for any given bearing, expressed in degrees between 0.0 (inclusive) and 360.0 (exclusive). ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 3 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 4 4

3 A worksheet contains rainfall data for Liverpool, NSW for the month of April 009, downloaded from http://www.bom.gov.au/climate/dwo/ A domestic water tank is fed from the guttering of a house. Given the roof area, tank capacity and initial amount of water in the tank, complete the worksheet using a VBA procedure. Assume no water is drawn from the tank over the month. Analysis: how much water does mm of rain produce per m of area? Named cells RoofArea and TankCapacity Summary Recursion is a natural way to express some algorithms tail recursion can be replaced by iteration care must be taken to avoid recursion that re-evaluates the same thing over and over drawing recursive pictures may help in understanding how recursion works Sometimes you need to think creatively about solutions Office apps can create and manipulate documents and data through the use each other s object models expressed in VBA. VBA fills in this column ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 5 ENGG8 UNSW, CRICOS Provider No: 00098G W9 slide 6 5