240 likes | 351 Views
Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 4, Functions Wednesday 30 June 2010. Two-week ISTE workshop on Effective teaching/learning of computer programming. Overview. Iterative Solution (Contd.)
E N D
Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 4, Functions Wednesday 30 June 2010 Two-week ISTE workshop onEffective teaching/learning of computer programming
Overview • Iterative Solution (Contd.) • Finding roots of a given function • Different ways of prescribing iteration • Functions • Need, definition and usage • Workshop Projects Lecture 4 Functions
Newton Raphson method Method to find the root of f(x), i.e. x such that f(x)=0. Method works if: f(x) and f '(x) can be easily calculated. and a good initial guess is available. Example: To find square root of k. use f(x) = x2 - k. f’ (x) = 2x. f(x), f’ (x) can be calculated easily. only few arithmetic operations needed Initial guess x0 = 1 It always works! can be proved. Lecture 4 Functions
Newton Raphson method Method to find the root of f(x), i.e. x such that f(x)=0. Method works if: f(x) and f '(x) can be easily calculated. and a good initial guess is available. Example: To find square root of k. use f(x) = x2 - k. f’ (x) = 2x. f(x), f’ (x) can be calculated easily. only few arithmetic operations needed Initial guess x0 = 1 It always works! can be proved. Let x = √k then x2 = k and x2 – k = 0 Lecture 4 Functions
How to get better xi+1 given xi Point A =(xi,0) known. Calculate f(xi ). Point B=(xi,f(xi)) is now known B Approximate f by tangent C= intercept on x axis C=(xi+1,0) A C xi+1 xi f(x) f’ (xi) = AB/AC = f(xi)/(xi - xi+1) xi+1 = (xi- f(xi)/f’ (xi)) Lecture 4 Functions
Square root of k xi+1 = (xi- f(xi)/f’ (xi)) f(x) = x2 - k, f’ (x) = 2x xi+1 = xi - (xi2 - k)/(2xi) = (xi + k/xi)/2 Starting with x0=1, we compute x1, then x2, and so on Each successive value of xi will be closer to the root We can get as close to sqrt(k) as required by carrying out these iterations many times Errors in floating point computations ? Lecture 4 Functions
Program segment // calculating square root of a number k 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; Lecture 4 Functions
Another way float xi, k; cin >> k; for( xi = 1 ; // Initial guess. Known to work. xi*xi – k > 0.001 || k - xi*xi > 0.001 ; //until error in the square is at most 0.001 xi = (xi + k/xi)/2); cout << xi; Lecture 4 Functions
Special ways of using ‘for’ for (xxx; yyy; zzz) { www } • In the alternate way we saw, the computations required for each iteration are all specified as part of the specifications of ‘for’ statement itself. • Thus the ‘body’ of statements (www) is missing, because it is not required • A special way of using ‘for’ for (; ; ) { www} • This specifies an infinite iteration, the loop must be broken by some condition within ‘www’ Lecture 4 Functions
Yet Another way float k; cin >> k; float xi=1; While (xi*xi – k > 0.001 || k - xi*xi > 0.001){ xi = (xi + k/xi)/2 ; } cout << xi; Lecture 4 Functions
While statement while (condition) { loop body}; check condition, if true then execute loop body. Repeat. If loop body is a single statement, then need not use { }. Always putting braces is recommended; if we later insert a statement, we may forget to put them, so we should do it at the beginning. Lecture 4 Functions
for and while If there is a “control” variable with initial value, update rule, and whose value distinctly defines each loop iteration, use ‘for’. Also, if loop executes fixed number of times, use ‘for’. Lecture 4 Functions
Functions • Consider a quadratic function f(x) = ax2 + bx + c f’(x)= 2ax + b • It would be nice, if we had separate blocks of instructions to calculate these for different values of x • A ‘function’ in c is such a separate block • It takes one or more parameters and returns a single value of a specified type Lecture 4 Functions
Example of functions float myfunction (float a, float b, float c, float x){ float value; value = a *x*x + b*x + c; return (value); } float myderivative(float a, float b, float x){ float value; value = 2*a*x + b; return (value); } Lecture 4 Functions
Syntax int myfunction (float a, …) { • First word tells the type of the value which will be returned. • Next is the name of the function, which we choose appropriately • This is followed by one or more parameters whose values will come from the calling instruction • Note the return statement: return (value); • this says what value is to be sent back. In general, it can be an expression which is evaluated when return statement is executed Lecture 4 Functions
Function in our model • We had thought of our computer as a dumbo, so imagine each such function to be evaluated by a separate assistant dumbo • Any time a function is invoked within an instruction which is executing, the given parameters are handed over to the assistant dumbo • Assistant dumbo calculates the function value and returns the same to main dumbo • Our main dumbo then onwards carries on from exactly where he left, using that returned value in place of the reference to the function Lecture 4 Functions
Invoking a function (function call) • Within a program, a function is invoked simply by using the function name (with appropriate parameters) within any expression • In the Newton Raphson method, we have a value xi, and we calculate next value using xi+1 = (xi- f(xi)/f’ (xi)) • Suppose our function was f(x) = ax2 +bx + c • Then we could design our program using the two functions which we have written (myfunction and myderivative) Lecture 4 Functions
Newton Raphson using function calls int main() { float x, a, b, c, root; // read a, b, c ... x = 1.0; // This is the initial guess for x for (int i=0; i < 10; i++){ x = (x - myfunction(a,b,c,x) /myderivative(a,b,x)); } ... } Lecture 4 Functions
Invocation rules • x = (x - myfunction(a,b,c,x)/ myderivative(a,b,x)); • When dumbo encounters ‘myfunction’ while evaluating the expression, • it suspends execution of the program, • goes over to the defined function with the available values of the parameters • calculates the value executing given instructions within that function • then returns back to the main program, replaces the reference to function by the returned value, and continues evaluation of the remaining expression. Lecture 4 Functions
Some points to ponder • We see that the calculations pertaining to our function evaluation have been separated out, perhaps resulting a better structured or ‘modular’ program • Why is this important • Suppose we wish to modify this same program to calculate a root of another function, then it is far easier to replace code only in that part where functions are defined. • Otherwise we may have to search our entire code to find which lines we should change Lecture 4 Functions
Some points to ponder ... • Can I use programming code for functions written by ohers • Yes, of course, that is the very idea • We can even compile those functions separately and link them with our program, but we need to include prototype definitions of these functions within the program • We can now understand why we say int (main) … and return 0; • Our entire program is actually treated as a function by the operating system Lecture 4 Functions
Question, From PSG Coimbatore: • If we declare an int variable , the largest value it holds varies from system to system. What is the reason behind this?
Question, From GEC_Thrissur: • How to return to value’s from a function at a time for example two roots of quadratic equation
Question, From NIT_Jalandhar • Can the main function return a float value