program newton
!  2008. 5. 14.  I. Tamagawa
implicit none

 real :: x1=10.0, x2, dx ! x1 is starting values for x
 real :: y1, y2, yc, dy, grad
 real :: eps = 1.0e-6	! Error for x
 integer :: count	! Loop counter
 real :: f, dfdx


write(*,*) 'count, dx,  dy,  x,   y'
! Loop 
 count = 0
 dx = eps * 10 !   
 y1 = f(x1)
 do while( dx > eps )
  grad = dfdx(x1)
  if( grad == 0 ) then
    write(*,*) 'Can not continue, because dy/dx=0'
    stop
  end if

  x2 = x1 - y1/grad
  dx = abs(x2-x1)
  y2 = f(x2)
  dy = abs(y2 - y1)
  x1 = x2
  y1 = y2
 
    count = count + 1
    write(*,*) count,  ',', dx, ',',dy, ',',x2, ',',y2
 end do
   
end 

real function f(x)
 real :: x
 real :: m=3, a=2	! should be same in function dfdx
 f = x**m -a
 return
end

real function dfdx(x)
 real :: x
 real :: m=3, a=2	! should be same in function f 
 dfdx = m*(x**(m-1))
 return
end
