function x- My Sqrt(a) ifa==0. x=0: else Two Power=1: m=A while m>=1. m=m/4: TwoPower =2*TwoPower end while m < 25 m*4: TwoPower TwoPower/2 end X=(1+2*m)3; for k=1: 4, x=(X+(m/x)/2; end x=X*Two Power end
function x = MySqrt(A) if A==0, x = 0; else TwoPower = 1; m = A; while m>=1, m = m/4; TwoPower = 2*TwoPower; end while m < .25 m = m*4; TwoPower = TwoPower/2; end x = (1+2*m)/3; for k=1:4, x = (x + (m/x))/2; end x = x*TwoPower; end
Relative Error in the Function MySqrt(A) 2.5 1.5 0.5 10 16
0 2 4 6 8 10 12 14 16 0 0.5 1 1.5 2 2.5 3 x 10 -16 Relative Error in the Function MySqrt(A) A
Bisection If a continuous function f(x) changes sign on an interval, then it must have at least one root in the interval while abs(a-b)> delta The while-loop may never if(a)*f(a+b)/2)<=0 terminate if delta is smaller than the spacing of the b=(a+b)2 floating point numbers else between a and b a=(a+b)/2 The second flaw is that it end requires two function evaluations per iteration ei root=(a+b)/2
Bisection If a continuous function f(x) changes sign on an interval, then it must have at least one root in the interval. while abs(a-b) > delta if f(a)*f((a+b)/2)<=0 b = (a+b)/2 else a = (a+b)/2 end end root = (a+b)/2; The while-loop may never terminate if delta is smaller than the spacing of the floating point numbers between a and b. The second flaw is that it requires two function evaluations per iteration
function noend(a, b, delta) noend(1000001,1001.0001,eps) noend(1000000001000000001eps) while abs(a-b)>delta if a=b, a=(a+b)/2; else, b=(a+b)/2 end i=i+1 if abs(a-b<eps*max(abs(a), abs(b) pause enc end
function noend(a,b,delta) i=1; while abs(a-b)>delta if a<=b, a=(a+b)/2; else, b=(a+b)/2; end i=i+1 if abs(a-b)<eps*max(abs(a),abs(b)) a pause end end noend(1000.0001,1001.0001,eps) noend(10000000.0001,10000001.0001,eps)
function root=Bisection(fname, a, b, delta) fa= feval(fname, a); fb=feval(fname, b) if fa*fb>0, displinitial interval is not bracketing. return end if nargin==3. delta=0: end while abs(a-b)>delta+eps*max(abs(a), abs (b) mid=(a+b)/2; mid =feval(fname, mid); if fa 'fmid <=0. b=mid: fb= fmid else. a=mid: fa= fmid: end en root=(a+b)/2
function root = Bisection(fname,a,b,delta) fa = feval(fname,a); fb = feval(fname,b); if fa*fb > 0, disp('Initial interval is not bracketing.') return;end if nargin==3, delta = 0;end while abs(a-b) > delta+eps*max(abs(a),abs(b)) mid = (a+b)/2; fmid = feval(fname,mid); if fa*fmid<=0, b = mid; fb = fmid; else, a = mid; fa = fmid; end end root = (a+b)/2;