> NewtonItr := proc()

#Here the convergence criterion is much more severe than usual. See comments.

local F,DF, p,deri, f1,d1, f2,d2, r,eps;

 

printf(`Enter a function:\n`);

F  :=scanf("%a")[1];

 

DF := unapply(diff(F,x),x);

F  := unapply(F,x);

 

printf(`Enter an initial point:\n`);

p := scanf(`%f`)[1];

deri := DF(p);

if abs(deri)< eps then printf("  deri=%6.3f\n",deri); RETURN(false); fi;

 

f1 := F(p);

d1 := -f1/deri;

printf("f(%20.15f)=%20.15f, deri=%6.3f, dx=%20.15f\n",

p,f1,deri,d1);

p := p+d1;

r := 0.5; #smaller r suggests higher threshold

eps := 10^(-7);

do

  f2 := F(p);

  if abs(f2/f1)< r then #function values tend to decrease

    deri := DF(p);

    if abs(deri)< eps then printf("  deri=%6.3f\n",deri); RETURN(false); fi;

    d2 := -f2/deri; #iterator

    printf("f(%20.15f)=%20.15f, deri=%6.3f, dx=%20.15f\n",

p,f2,deri,d2);

    p := p+d2;

    if abs(d2^2/(d1-d2))< eps then #d2 is much smaller than d1

      printf("f(%20.15f)=%20.15f, deri=%6.3f, dx=%20.15f\n",

p,F(p),DF(p),-F(p)/DF(p));

      printf("Converge to approximate root x=%20.15f\n",p);

      RETURN(true); #success exit

    else

      f1:=f2; d1:=d2;

    fi;

  else

    printf("f(%20.15f)=%20.15f, deri=%6.3f, dx=%20.15f\n",

p,f2,DF(p),-F(p)/DF(p));

    printf( "  f1 : f2 = %f : %f\n",f1,f2);

    RETURN(false); #failure exit

  fi;

od;

 

end: