!  derchk    This program plots g(x) and (f(x+dx)-f(x))/dx
!            on the interval [a,b] which is inside of the rectangle 
!            { (x,y) : xmin < x < xmax  &  ymin < y < ymax }

def f(x)=sin(x^2)                  ! the function to be differentiated
def df(x)= (f(x+dx)-f(x))/dx       ! numerical derivative of f
def g(x)=2*x*cos(x^2)              ! hopefully the derivative of f

let a= -3            ! [a,b] is the interval on which f(x) is to plotted
let b=  -a

let xmin = a         ! left edge of screen
let xmax = b         ! right edge of screen
let ymin = -6        ! bottom of screen
let ymax = -ymin         ! top of screen      y/x ratio of about 2/3 is good

let n=217
let dx=(b-a)/n         ! this determines the smoothness of the plot

sub plotdf
  set color "green"
  plot a,df(a);
  for x=a to b step dx
     let y=df(x)
     plot x,y;
     if y > ymax or y < ymin then plot  
  next x
  plot
end sub

sub plotg
  set color "yellow"
  plot a,g(a);
  for x=a to b step dx
     let y=g(x)
     plot x,y;
     if y > ymax or y < ymin then plot  
  next x
  plot
end sub

sub drawaxis
  set window xmin,xmax,ymin,ymax    ! determines screen coordinates
  set color "red"
  box lines xmin,xmax,ymin,ymax     ! red outline drawn
  set color "white"
  plot xmin,0 ; xmax,0              ! draw axis
  plot 0,ymin ; 0,ymax
  set text justify "left","top"
  plot text, at xmin,0: str$(xmin)  ! label axis
  set text justify "right","top"
  plot text, at xmax,0: str$(xmax)
  set text justify "left","bottom"
  plot text, at 0,ymin: str$(ymin)
  set text justify "left","top"
  plot text, at 0,ymax: str$(ymax)
  set color "green"
  set text justify "center","top"
  if a<>xmin then plot text,at a,0 : str$(a)  ! label a,b
  if b<>xmax then plot text,at b,0 : str$(b)
end sub

! main program
  set mode "egahires"
  open #1 : screen .2,.7,.05,.45
  call drawaxis
  call plotdf
  box keep xmin,xmax,ymin,ymax in upic$
  open #2 :  screen .2,.7,.5,.9
  call drawaxis
  call plotg
  box keep xmin,xmax,ymin,ymax in lpic$
  get key key
  open #3 :  screen 0,1,0,1
  box show lpic$ at 0,0
  box show upic$ at .5,.5
  for y=0 to .5 step .01
    box show lpic$ at y,y using "xor"
    box show lpic$ at y,y using "xor"
    sound 1500/(y+.01),.1
  next y
play "o4 l4 c c e g o5 l2 c. o4 a."
end
