c
c
c     ###################################################
c     ##  COPYRIGHT (C)  1997  by  Jay William Ponder  ##
c     ##              All Rights Reserved              ##
c     ###################################################
c
c     ##################################################################
c     ##                                                              ##
c     ##  function maxwell  --  Maxwell-Boltzmann distribution value  ##
c     ##                                                              ##
c     ##################################################################
c
c
c     "maxwell" returns a speed in Ang/sec randomly selected from a
c     3-D Maxwell-Boltzmann distribution for the specified particle
c     mass and system temperature
c
c     literature reference :
c
c     P. W. Atkins, "Physical Chemistry, 4th Edition", W. H. Freeman,
c     New York, 1990; see section 24.2 for general discussion
c
c
      function maxwell (mass,temper)
      implicit none
      include 'math.i'
      include 'units.i'
      integer iter,maxiter
      real*8 maxwell,mass,temper
      real*8 rho,random,erf,erfinv
      real*8 speed,beta,delta
      real*8 error,derror,term
c
c
c     pick a random cumulative probability distribution value
c
      rho = random ()
c
c     use the 1-D distribution value as an initial guess
c
      beta = sqrt(mass / (2.0d0*boltzmann*temper))
      speed = erfinv (rho) / beta
c
c     apply Newton's method to correct to the 3-D distribution
c
      delta = 0.00000001d0
      maxiter = 20
      error = 1.0d0
      iter = 0
      dowhile (abs(error).gt.delta .and. iter.lt.maxiter)
         iter = iter + 1
         term = (2.0d0/sqrtpi) * beta * speed * exp(-(beta*speed)**2)
         error = rho + term - erf (beta*speed)
         derror = 2.0d0 * term * beta**2 * speed
         speed = speed + min(error/derror,2.0d0*speed)
      end do
c
c     set the final converged value of the particle speed
c
      maxwell = speed
      return
      end
