CS101: Numerical Computing 2 Abhiram Ranade. Topics More examples of for statement  Evaluating e x.  Hemachandra Numbers  Newton Rhapson method for.

Slides:



Advertisements
Similar presentations
Methods Java 5.1 A quick overview of methods
Advertisements

Computer Programming w/ Eng. Applications
1 Chapter Six Algorithms. 2 Algorithms An algorithm is an abstract strategy for solving a problem and is often expressed in English A function is the.
Computer Science 1620 Loops.
Chapter 6: User-Defined Functions I
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6: User-Defined Functions I
Chapter 4: Looping CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Fundamentals of Python: From First Programs Through Data Structures
Agenda Review Compiling Review Data Types Integer Division Composition C++ Mathematical Functions User Input Reading: , 8.11 Homework #3.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
Fundamentals of Python: First Programs
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
CS 101: Arrays Abhiram Ranade. Computers manipulate many objects Given the position, masses, and velocities of all stars, where will they be after the.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
CS 101: Numerical Computing Abhiram Ranade. Representing Integers “int x;” : reserves one cell in memory for x. One cell: “One word” has 32 capacitors.
Numerical Methods Applications of Loops: The power of MATLAB Mathematics + Coding 1.
CSE1222: Lecture 4The Ohio State University1. Mathematical Functions (1)  The math library file cmath Yes, this is a file with definitions for common.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
CS 101: “If” and Recursion Abhiram Ranade. This week’ lab assignment: Write a program that takes as input an integer n and a sequence of numbers w1,w2,...,wn.
CSCI 125 & 161 Lecture 13 Martin van Bommel. Floating Point Data Floating point numbers are not exact Value 0.1 in binary is very close to 1/10, but not.
CPS120 Introduction to Computer Science Iteration (Looping)
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Data Structures Chapter 1- Introduction Mohamed Mustaq.A.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Loop Application: Numerical Methods, Part 1 The power of Matlab Mathematics + Coding.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
Numerical Methods.
1 CS161 Introduction to Computer Science Topic #9.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Numerical Methods Solution of Equation.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
CPS120 Introduction to Computer Science Iteration (Looping)
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Review Expressions and operators Iteration – while-loop – for-loop.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Intro. to Computer Programming Eng. Nehal A. Mohamed Spring Semester-2016.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Chapter 6: User-Defined Functions I
Functions.
Formatted and Unformatted Input/Output Functions
Iteration with While You can say that again.
Coding Concepts (Basics)
Chapter 6: User-Defined Functions I
Loops.
Introduction to the Lab
Presentation transcript:

CS101: Numerical Computing 2 Abhiram Ranade

Topics More examples of for statement  Evaluating e x.  Hemachandra Numbers  Newton Rhapson method for finding roots Defining Functions

exex We use the series e x = 1 + x + x 2 /2! + x 3 /3! +... We will evaluate the series to some 10 terms. ith term is x i /i!. How can we calculate it quickly? Direct method: write a loop to calculate x i and also i!, then divide. loops within loop.

Better idea ith term = x i /i! = x i-1 /(i-1)! * (x/i) = i-1th term * (x/i) So we calculate ith term from the i-1th term calculated earlier, rather than directly.

Program float x; cin >> x; float term = 1.0; // 0th term of the series. float answer = 0.0; for( int i=1; i <= 10; i++){ answer += term; term = term * x / i;} cout << answer;

Notes You must put the following comment to your program: /* After ith iteration, i terms of the series have been summed up */ Check that this is true! - by inspection, - Add a statement to print after each iteration and check.

Program 2 float x; cin >> x; float term = 1; // 0th term of the series. float answer = 0; for( int i=1; term > ; i++){ answer += term; term = term * x / i;} cout << answer;

Remarks If we calculate x i /i! independently in each iteration, we will need about 2i arithmetic operations in each iteration. In our program, we just need 2 in each iteration. Idea of reusing what was calculated in the previous iteration is very important, and also very commonly useful.

Hemachandra’s Problem (12th century AD) Suppose I have to build a wall of length 8 feet. I have bricks 2 feet long and also 1 foot long. In how many ways I can lay the bricks so that I fill the 8 feet? Possiblities: 2,2,2,2; 1,1,1,1,1,1,1,1; 2,2,2,1,1....

Hemachandra’s Actual Problem Suppose I am designing a poetic meter with 8 beats. The meter is made of short syllables and long syllables. Short syllable = 1 beat, Long syllable = 2 beats. How many ways are there of filling 8 beats? Example of a poetic meter Aa ji chya Ja wa lii gha dya l ka sa lay aa he ch mat kaa ri k ya kun den du tu sha r ha r dha va la ya shubh r vas tra vru ta l l l s s l s l s s s l l l s l l s s

Hemachandra’s Solution “By the method of Pingala, it is enough to observe that the last beat is long or short” Pingala: mathematician/poet from 500 A.D. Hemachandra is giving credit to someone who lived 1500 years before him!! Copy but give credit..

Hemachandra’s solution contd. S : Class of 8 beat patterns with short last beat. L : Class of 8 beat patterns with long last beat. Each 8 beat pattern is in class L or class S S = all 7 beat patterns + long beat appended. | class S | = Number of patterns with 7 beats | class L | = Number of patterns with 6 beats |8 beat patterns| = |class S| + |class L| = |7 beat patterns| + |6 beat patterns|

Algebraically.. H n = number of patterns with n beats H 8 = H 7 + H 6 In general H n = H n-1 + H n-2 Does this help us to compute H 8 ? We need to know H 7, H 6, for which we need H 5,...

Algorithm Idea H 1 = number of patterns with 1 beat = 1 H 2 = Number with 2 beats = 2...{SS, L} H 3 = H 2 + H 1 = = 3 H 4 = H 3 + H 2 = = 5 H 5 = H 4 + H 3 = = 8 H 6 = H 5 + H 4 = = 13 H 7 = H 6 + H 5 = = 21 H 8 = H 7 + H 6 = = 34...

Program to compute H n int n; cin >> n; // which number to compute int hprev = 1, hcurrent = 2; for(int i=3; i <= n; i++){ hnext = hprev + hcurrent; hprev = hcurrent; // prepare for next iteration hcurrent = hnext; } cout << hnext;

Code is tricky! Need a comment: /* At the begining of an iteration hcurrent = H i-1 write h[i] if you like. hprev = H i-2 where i is the value of variable i */ Can you prove this? Will mathematical induction help? Proving this is enough -- hnext = hprev + hcurrent -- hence correct answer will be generated.

Proof by induction Base case: At the beginning of the first iteration is this true? Yes, i will have value 3, and hprev = 1 = H 1, hcurrent = 2 = H 2 Suppose it is true at some later iteration, when i has value v >= 3. By induction hypothesis hprev, hcurrent have values H v-1,H v-2. The first statement hnext = hprev + hcurrent makes hnext = H v-1 + H v-2 = H v. After this the statement hprev = hcurrent makes hprev = H v-1. The next statement hcurrent = hnext makes hcurrent=H v. In the next iteration i will have value v+1. But hprev,hcurrent will have exactly the right values!

On Hemachandra Numbers Series is very interesting. Number of petals in many flowers. Ratio of consecutive terms tends to a limit. What are these numbers more commonly known as? Hemachandra lived before Fibonacci. Mathematics from poetry!

Newton Raphson method Method to find the root of f(x), i.e. x s.t. f(x)=0. Method works if:  f(x) and f '(x) can be easily calculated.  A good initial guess is available. Example: To find square root of k.  use f(x) = x 2 - k. f ‘ (x) = 2x.  f(x), f ‘ (x) can be calculated easily. 2,3 arithmetic ops.  Initial guess x 0 = 1 always works! can be proved.

How to get better x i+1 given x i f(x) xixi x i+1 Point A =(x i,0) known. A B C f ‘ (x i ) = AB/AC = f(x i )/(x i - x i+1 )  x i+1 = (x i - f(x i )/f ‘ (x i )) Calculate f(x i ). Point B=(x i,f(x i )) known Approximate f by tangent C= intercept on x axis C=(x i+1,0)

Square root of k x i+1 = (x i - f(x i )/f ‘ (x i )) f(x) = x 2 - k, f ‘ (x) = 2x x i+1 = x i - (x i 2 - k)/(2x i ) = (x i + k/x i )/2 Starting with x 0 =1, we compute x 1, then x 2, then... We can get as close to sqrt(k) as required. Proof not part of the course.

Code float k; cin >> k; float xi=1; // Initial guess. Known to work. for(int i=0; i < 10; i++){ // 10 iterations xi = (xi + k/xi)/2; } cout << xi;

Another way float xi, k; cin >> k; for( xi = 1 ; // Initial guess. Known to work. xi*xi – k > || k - xi*xi > ; // until error in the square is at most xi = (xi + k/xi)/2); cout << xi;

Yet Another way float k; cin >> k; float xi=1; while(xi*xi – k > || k - xi*xi > 0.001){ xi = (xi + k/xi)/2 ; } cout << xi; }

While statement while (condition) { loop body} check condition, then execute loop body if true. Repeat. If loop body is a single statement, then need not use { }. Always putting braces is recommended; if you insert a statement, you may forget to put them, so do it at the beginning. True for other statements also: for/repeat/if.

For vs. while If there is a “control” variable with initial value, update rule, and whose value distinctly defines each loop iteration, use for. If loop executes fixed number of times, use for. Personal taste. “break” and “continue” : read from your book.

Procedures which return values Polygon(sides, length) draws. But it will be nice to have a procedure sqrt which can be called as y = sqrt(2.56); // should return 1.6 which would suspend the current program, compute sqrt(k), send back the value, and resume. This is possible!

Procedure for sqrt float sqrt(float k){ float xi=1; while(xi*xi – k > || k - xi*xi > 0.001){ xi = (xi + k/xi)/2 ; } return xi; }

Notes First word tells the type of the value being returned. Note the return statement: this says what value is to be sent back. Other nomenclature is same. Parameters (k), argument (2.56 in our example). “y = sqrt(2.56);” is a “call”.

Execution Mechanism Almost identical to what was described earlier. Calling program suspends. Area constructed for sqrt procedure. Argument value (2.56) copied to k from main program. Sqrt program executes in its own area. After it finishes, result (1.6 if it works) is copied back to calling program. The result replaces the call. Area in which sqrt executed is destroyed. Calling program resumes.

Notes In C++ procedures are called functions. Uniform syntax for functions that do not return values. So far we have used: “ procedure Polygon(...)...” Instead in C++ it is more common to write “ void Polygon(...)...” “Procedure” was a keyword defined only for this course, stop using it from now on.

Math library You didnt actually need to write the sqrt function. Just add the line: #include at the top of your file. This allows you to use in your program the mathematical functions in the cmath library. sqrt is in the library. So are functiones such as sine, cos, tan,...

Homework Write a program to calculate the cube root using Newton Raphson method. Check how many iterations are needed to get good answers. Should be very few. Use sqrt function to draw a right angled isoceles triangle.