Introductory Programming Fall 2005 Evaluation 10 on Thursday (last one) Two solutions to Evaluation 9: a) In testsqrt.m: function testsqrt(v) for x=v mine = mysqrt(x); theirs = sqrt(x); diff = mine-theirs; rel = diff / theirs end end b) In mysqrt.m: function root = mysqrt(a) est = a; for i=1:5 est = est - f(est, a) / fp(est); end root = est; end function y = f(x, b) y = x^2 - b; end function y = fp(x) y = 2*x; end Who calls who? 1) testsqrt calls mysqrt and sqrt (notice the symmetry) 2) mysqrt calls f and fp (notice the encapsulation) (why do we have to pass a as an input variable to f?) 3) draw the stack diagrams here... Nested functions ---------------- One way to avoid passing values around as input variables is to use nested functions: function root = mysqrt(a) % a is defined here... function y = f(x) y = x^2 - a; % and used here... end function y = fp(x) y = 2*x; end est = a; % and here. for i=1:5 est = est - f(est) / fp(est); end root = est; end Relative error -------------- What does relative error tell us about the number of correct digits? How does the error for the sqrt algorithm depend on x? How can we iterate until convergence in MATLAB? What does the following loop do? i = 0 while i<10 i = i + 1 end What about this one? x = a; while true xnew = (x + a/x) / 2 if abs(xnew - x) < 1e-6 break end x = xnew; end r = xnew;