newton Subroutine

subroutine newton(f, xinit, eps, Niter)

Arguments

Type IntentOptional Attributes Name
function f(x)
Arguments
Type IntentOptional Attributes Name
real(kind=8) :: x
Return Value real(kind=8)
real(kind=8), intent(inout) :: xinit
real(kind=8), optional :: eps
integer, optional :: Niter

Source Code

subroutine newton(f,xinit,eps,niter)
  interface
     function f(x)
       real(8) :: x
       real(8) :: f
     end function f
  end interface
  real(8), intent(inout) :: xinit
  real(8),optional       :: eps
  integer,optional       :: Niter
  real(8)                :: root
  real(8)                :: dh = 1d-4
  real(8)                :: fx1
  real(8)                :: fx2
  real(8)                :: fprime
  real(8)                :: x
  real(8)                :: xnew
  integer                :: i
  real(8)          :: eps_
  integer          :: Niter_
  !
  eps_=1d-9;if(present(eps))eps_=eps
  Niter_=200;if(present(Niter))Niter_=Niter
  !
  Root  = 0d0
  x = xinit
  do i = 1,niter_
     fx1    = f(x)
     fx2    = f(x+dh)
     fprime = (fx2 - fx1) / dh
     xnew   = x - fx1 / fprime
     if ( abs(xnew-x) <= eps_ ) then
        root  = xnew
        xinit = root
        exit
     endif
     x = xnew
  enddo
end subroutine newton