ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing

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

Mathematics 350 Section 6.3 Introduction to Fractals

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

European Computer Driving Licence. Advanced Spreadsheet Software BCS ITQ Level 3. Syllabus Version 2.0

Transformation, tessellation and symmetry line symmetry

Surveying Prof. Bharat Lohani Indian Institute of Technology, Kanpur. Lecture - 1 Module - 6 Triangulation and Trilateration

Computer Graphics Fundamentals. Jon Macey

(Refer Slide Time: 02.06)

Using Microsoft Excel

Rotated earth or when your fantasy world goes up side down

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

Name: Tutor s

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

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

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

Teach Yourself Microsoft PowerPoint Topic 4: Slide Master, Comments and Save Options

Chapter 2 Assignment (due Thursday, April 19)

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

CS 112 Introduction to Programming

PRACTICAL GEOMETRY SYMMETRY AND VISUALISING SOLID SHAPES

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

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

Excel. Spreadsheet functions

MathZoom, Summer, 2014

Ms Excel Vba Continue Loop Through Range Of

ENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration

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

UNIT 5A Recursion: Basics. Recursion

Angles, Straight Lines and Symmetry

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

Using Excel to produce graphs - a quick introduction:

Mesh Generation. Quadtrees. Geometric Algorithms. Lecture 9: Quadtrees

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

How shapes are represented in 3D Graphics. Aims and objectives By the end of the lecture you will be able to describe

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

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

Teaching Engineering Analysis Using VBA for Excel. Abstract. Introduction

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

Unit 5: Recursive Thinking

Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7

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

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

Introduction to Software Development (ISD) Week 3

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

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

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

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

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

Describe the Squirt Studio

COMP1000 / Spreadsheets Week 2 Review

Right Angle Triangle. Square. Opposite sides are parallel

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

6.001 Notes: Section 4.1

Mathematics 308 Geometry. Chapter 9. Drawing three dimensional objects

Civil Engineering Computation

It is useful for the user of this software to keep in mind the following points:

2013 Four-by-Four Competition Thursday, January 31st, Round Four-by-Four Competition Thursday, January 31st, 2013.

Chapter 2 Assignment (due Thursday, October 5)

Creating a Box-and-Whisker Graph in Excel: Step One: Step Two:

Self-Teach Exercises: Getting Started Turtle Python

Data. Selecting Data. Sorting Data

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

Using Microsoft Word. Working With Objects

Excel 2013 Intermediate

This document should only be used with the Apple Macintosh version of Splosh.

Excel Tips for Compensation Practitioners Month 1

Range Objects and the ActiveCell

Using Flash Animation Basics

Charts in Excel 2003

version staff had them to share viewing this this user guide. >Reports, as Logging In the SQL login User Name for your district. perform the guides.

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

How to Create a For Next Loop in Excel VBA!

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

Spreadsheet Concepts: Creating Charts in Microsoft Excel

(Refer Slide Time: 00:02:00)

2016 ACM ICPC Southeast USA Regional Programming Contest. Division 1

IP4 - Running reports

Lastly, in case you don t already know this, and don t have Excel on your computers, you can get it for free through IT s website under software.

1. Complete these exercises to practice creating user functions in small sketches.

Outline. Writing Functions and Subs. Review Immediate (1-line) Errors. Quiz Two on Thursday (2/23) Same Code Without Option Explicit

I/A Series Software Spreadsheet

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut

Week - 01 Lecture - 04 Downloading and installing Python

1. One-third of 105 is the same as seven-sixths of what number? 1.

Coordinates - Activity 1 Plotting whole number ordered pairs.

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

A Tutorial for Excel 2002 for Windows

Lecture 19: Recursion

Ms Excel Vba Continue Loop Through Columns Range

CSV Roll Documentation

Microsoft Excel XP. Intermediate

Reflections, Translations, and Dilations

outlook-vba #outlookvba

5 th Grade Hinojosa Math Vocabulary Words

a function that calls itself It doesn t do anything! Defining a recursive function 1) divide and conquer 2) base case 6/21/2018 chapter 15

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

Section 8 Formatting

Computer Graphics 4731 Lecture 5: Fractals. Prof Emmanuel Agu. Computer Science Dept. Worcester Polytechnic Institute (WPI)

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Stage 1 Intermediate Revision Sheet

Transcription:

ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 1

This Week Wednesday am: Will include discussion about assignment 2 Wednesday pm: Will include VBA exam revision examples References Recursion is covered quite nicely at http://www.cs.princeton.edu/introcs/23recursion/ not quite so well in Chapra Section 12.4 Recursion ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 2

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 Else End If fact = 1 End Function fact = n * fact(n-1) ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 3

Tracing Factorial Trace the calculation as with other procedure calls fact(5) = 5 * fact(4) fact(4) = 4 * fact(3) fact(3) = 3 * fact(2) Each function waits for the recursive call to return fact(2) = 2 * fact(1) fact(1) = 1 * fact(0) fact(0) = 1 fact(1) = 1 * 1 = 1 fact(2) = 2 * 1 = 2 fact(4) = 4 * 6 = 24 fact(5) = 5 * 24 = 120 fact(3) = 3 * 2 = 6 Each function uses the value from the recursive call to calculate and return its factorial ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 4

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 ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 5

The Dark Side of 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 <= 1 Then Else End If BadFib = 1 End Function BadFib = BadFib(n-1) + BadFib(n-2) * Regrettably, this is the solution to Chapra s misguided exercise 6, page 417 ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 6

tree has n levels Why BadFib is Bad Tracing calls on BadFib produces a tree rather than a simple stack of calls: F(3) is evaluated three times independently F(5) F(6) F(4) F(4) F(3) F(3) F(2) F(3) F(2) F(2) F(1) F(2) F(1) F(1) F(0) F(2) F(1) F(1) F(0) F(1) F(0) F(1) F(0) F(1) F(0) ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 7

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/bridges2005/burns/index.html ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 8

Fractals Although fractals are not necessarily recursive, they also show self-similarity. This is my favourite, a Newton-Raphson fractal: The picture shows part of the complex plane (Re ±1.6, Im ±1.2). Colours represent how many iterations the N-R algorithm* takes to find a cube root of 1 given that starting point. The dark blue dots are the three roots. Colour coding: blue=1 to 3 iterations, yellow=8, red=12, white=16+. * The Newton-Raphson algorithm for finding the roots of f (x) was described in the lecture on iteration (week 7, slide 8). It applies to complex as well as real functions. ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 9

Fractal Self-Similarity More detail is revealed (with the same repeated alien patterns) as the limits are adjusted. The final version s area is 0.06 x 0.04, and white now represents 21+ iterations. ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 10

Recursive Drawings We can do a tiny bit of this with the simple drawing tools available in VBA Draw a simple figure, then one or more 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) Source: Wikipedia ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 11

pic: http://renambot.lakephoto.org/classes/488/lecture13.html Sierpinski Gasket One of the simplest fractals is the Sierpinski gasket, which consists of a triangle with smaller inverted triangular cutouts. Each level removes (or overlays) a white triangle, then applies the same algorithm recursively to each of the surrounding black regions Number of black triangles at depth n is 3 n, but how many white inverted triangles are there? try the Java applet at http://ejad.best.vwh.net/java/fractals/sierpinski.shtml ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 12

Recursive Drawing Procedure General approach: Sub DrawThing(x As Single, y As Single, size As Single) If size < MIN_SIZE Then End If Exit Sub draw figure at position (x, y) ' calculate position of first copy x1 = : y1 = DrawThing(x1, y1, size*scale_factor) ' same for other copies DrawThing(x1, y1, size*scale_factor) End Sub Constant describing the smallest effective size Constant describing the reduction in size for each copy ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 13

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 1, one connected to each tip of the H with the additional provisos that the H-trees of order n 1 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) ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 14

size H-Trees Apart from drawing a canvas, the algorithm for drawing an H-Tree centred on (x,y) is just (x+hsize,y-hsize) HTree(x,y,size) :- If size < MIN_SIZE Then Exit Sub End If hsize = size/2 ' half-size 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 (x,y) Use a separate subprogram to draw the lines, so you can apply the attributes consistently and once only hsize ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 15

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 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. ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 16

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) Other kinds of interface (if you re interested) Loading data into Excel from a table on a web page (but easier via the UI) Opening a browser window with a specified URL (which may include parameters) ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 17

Example: Creating a Word Doc ' 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(1).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 ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 18

Object Reference Settings Unfortunately this fails to satisfy the compiler. The error points to Word.Application Select Tools References on the VBE menu, scroll to Microsoft Word 12 * Object Library and check. Press OK. * or largest value: 10=Office2002, 11=Office2003, 12=Office2007, 14 = Office2010 (there is no 13!) ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 19

Worked Examples 1 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 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 110 degrees (slightly South of East), the back bearing is 290 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). ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 20

Worked Examples 2 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. ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 21

3 Worked Examples A worksheet contains rainfall data for Liverpool, NSW for the month of April 2009, 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 1mm of rain produce per m 2 of area? Named cells RoofArea and TankCapacity VBA fills in this column ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 22

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. ENGG1811 UNSW, CRICOS Provider No: 00098G W10 slide 23