! newtchat
!   Control:  just hit return    control break or `q' to end program
! NEWTROD  TRU   Shows newton method geometrically written by Rod Smart
! NEWTSPIR TRU   Gives a spiralling convergence picture
! NEWTCHAT TRU   Starting too far away   chatters
! NEWTON   TRU   First do split 10 ; mode 40   Show code
!                I modified code to show iterative method   x=(x+1)^(1/5)
!                Also told story about autopilots and starting guess.

def f(x)= x*(x-1)*(x-2)+1
def fp(x)= 3*x^2 -6*x + 2

sub init
 let a= -2
 let b= 3
 let xmin=-2
 let xmax= 3
 let ymin= -3
 let ymax= 4
 let inset=.2
 open #1: screen .05,.9,.05,.9
 set mode "egahires"
 window #1
 set window xmin,xmax,ymin,ymax
 clear
 box lines  xmin,xmax,ymin,ymax
 plot text, at inset,ymax-inset : "Newton's method"
 plot xmin+inset,0 ; xmax-inset,0
 plot 0,ymin+inset ; 0,ymax-inset
end sub

sub graphfunction
  window #1
  set color "white"
  let m=100
  let dx = (b-a)/m
  let x=a
  let  y = f(x)
  plot x,y ;
  for i = 1 to m
    let x=x+dx
    let y = f(x)
    plot x,y;
  next i
end sub

! main program

call init
call graphfunction
let x=1
let i=0
do
  call dotline(x,0,x,f(x),8)
  plot text, at x,f(x) : "x"&str$(i)
  set cursor 1,1
  print x
  let nextx = x - f(x)/fp(x)
  plot x,f(x); nextx,0
  let x=nextx
  let i=i+1
  get key key
loop  until chr$(key) = "q"

end

sub dotline(a,b,c,d,n)
  let dx= (c-a)/n
  let dy= (d-b)/n
  let x=a
  let y=b
  plot                ! beam off
  plot x,y;
  for i=1 to n step 2
    let x= x + dx
    let y= y + dy
    plot x,y
    let x= x + dx
    let y= y + dy
    plot x,y;
  next i
end sub
