Newton's Method implemented several ways. Videos of the programming:
http://www.youtube.com/watch?v=JnKkuPNr4P4
Click the video description for parts 2 and 3. Source code below.
Style 1: Expect user to enter function into F1 in the function app, and guess and tolerance are hardcoded.
Style 2: Provide a graphical interface for user input; automatically creates UI when run from program catalogue
Style 3: Bypass graphical interface; create a function instead
Style 4: Expect f(x) in F1 but still have function interface for Newton's Method (to get around a small issue with running from program catalogue)
Style 1: Initial attempt as a solution to a specific problem
export NEWT()
begin
local n,xold,xnew,err;err:=.000001;
n:=0;
xnew:=2;
xold:=xnew-2*err;
F0:=expr("'X-F1(X)/(" + diff(F1(X),X) + ")'");L1:={};
while (abs(xnew-xold)>err and n<100) do
n:=n+1;
L1(n):=xnew;
xold:=xnew;
xnew:=F0(xold);
end;L1(n+1):=xnew;
end;
Syle 2: Creating a user interface
export NEWT2()
begin
local n,xold,xnew,err,N,f;N:=100; err:=.00001; xnew:=1;
if input(
{f,xnew,err,N},
"Newton's Method",
{"f(X)=", "Guess=", "Error=", "Max Iter.="},
{
"Enter the function surrounded by single quotes",
"Enter the initial guess",
"Enter the tolerance",
"Enter the maximum number of iterations"
},
{f,xnew,err,N}
) then
F1:=f;CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);end;
end;
Style 3: Function-like command
export NEWT3(f,guess,tol,maxiter)
begin
local n,xold,xnew,err,N;N:=maxiter;
err:=tol;
xnew:=guess;
F1:=f;CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);
end;
Style 4: Mix of Style 1 and 3
export NEWT3(guess,tol,maxiter)
begin
local n,xold,xnew,err,N;N:=maxiter;
err:=tol;
xnew:=guess;
// F1:=f;CAS("F0:=id-F1/F1'");
L1:={}; L1(1):=xnew;
for n from 2 to N+1 do
xold:=xnew;
xnew:=F0(xold);
L1(n):=xnew;
if abs(xnew-xold)<err then break; end;
end;
editlist(L1);
end;