#C2.txt Jan. 27, 2014 Help:=proc() print(`B1(f,x,a,b), B(f,x,a,b,eps)`): print(`NR1(f,x,x0), NR(f,x,x0,N),TestNewton(f,x,x0,eps)`): end : #B1(f,x,a,b): inputs an expression (like x^3-2) #in a variable x, a variable x, and two (RATIONAL!) NUMBERS #and outputs FAIL if subs(x=a,f) and subs(x=b,f) have #the same sign a,a or b,b if of them is zero #and either a,c or c,b (where c=(a+b)/2) is where #f changes sign B1:=proc(f,x,a,b) local c: if subs(x=a,f)=0 then RETURN(a,a): elif subs(x=b,f)=0 then RETURN(b,b): elif sign(subs(x=a,f)*subs(x=b,f))=1 then RETURN(FAIL): else c:=(a+b)/2: if sign(subs(x=a,f)*subs(x=c,f))=-1 then RETURN(a,c): else RETURN(c,b): fi: fi: end: B:=proc(f,x,a,b,eps) local frank: frank:=B1(f,x,a,b): if frank=FAIL or frank[1]-frank[2]=0 then RETURN(frank): fi: while abs(frank[1]-frank[2])>eps do frank:=B1(f,x,frank): od: frank: end: #NR1(f,x,x0): inputs an expression f in x, #a variable x, and an initial guess x0 #and peforms ONE iteration in the Newton-Raphson method NR1:=proc(f,x,x0) #x0->x0-f(x0)/f'(x0)) x0- subs(x=x0,f)/subs(x=x0,diff(f,x)): end: #NR(f,x,x0,N): performs N iterations in Newton NR:=proc(f,x,x0,N) local x1,i: x1:=x0: for i from 1 to N do x1:=NR1(f,x,x1): od: x1: end: #TestNewton(f,x,x0,eps,N): inputs an expression #f in the variable x, an intial guess x0, a small eps #and a pos. integer N , and outputs the successive errors #abs(xn-alpha) for n from 1 to N where alpha is the #appx. to the root of f(x)=0 found by the bisection method TestNewton:=proc(f,x,x0,eps,N) local i,L,alpha,x1: alpha:=B(f,x,x0-2,x0+2,eps): if alpha=FAIL then RETURN(FAIL): fi: L:=[]: x1:=x0: for i from 1 to N do x1:=NR1(f,x,x1): L:=[ op(L), abs(x1-alpha[1])]: od: L: end: