NAG Library Manual, Mark 28.3
Interfaces:  FL   CL   CPP   AD 

NAG AD Library Introduction
Example description
    Program c05qd_p0w_fe
!     C05QD_P0W_F Example Main Program

!     Mark 28.3 Release. NAG Copyright 2022.

!     .. Use Statements ..
      Use iso_c_binding, Only: c_ptr
      Use nagad_library, Only: c05qd_p0w_f
      Use nag_library, Only: nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: mode = 2, n = 7, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: ad_handle
      Real (Kind=nag_wp)               :: epsfcn, factor, xtol
      Integer                          :: i, ifail, irevcm, ml, mu
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diag(:), fjac(:,:), fvec(:), qtf(:), &
                                          r(:), rwsav(:), x(:)
      Real (Kind=nag_wp)               :: ruser(5)
      Integer, Allocatable             :: iwsav(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..

      Write (nout,*) 'C05QD_P0W_F Example Program Results'

      Allocate (diag(n),fjac(n,n),fvec(n),qtf(n),r(n*(n+                       &
        1)/2),x(n),rwsav(4*n+10),iwsav(17))

!     The following starting values provide a rough solution.
      x(1:n) = -1.0_nag_wp

      ruser(1) = -1.0_nag_wp
      ruser(2) = 3.0_nag_wp
      ruser(3) = -2.0_nag_wp
      ruser(4) = -2.0_nag_wp
      ruser(5) = -1.0_nag_wp

      xtol = sqrt(x02ajf())
      diag(1:n) = 1.0_nag_wp
      ml = 1
      mu = 1
      epsfcn = 0.0E0_nag_wp
      factor = 100._nag_wp
      irevcm = 0

revcomm: Do

        ifail = 0
        Call c05qd_p0w_f(ad_handle,irevcm,n,x,fvec,xtol,ml,mu,epsfcn,mode,     &
          diag,factor,fjac,r,qtf,iwsav,rwsav,ifail)

        Select Case (irevcm)
        Case (1)
!         Monitoring exit.
          Cycle revcomm
        Case (2)
          Do i = 1, n
            fvec(i) = (ruser(2)+ruser(3)*x(i))*x(i) - ruser(5)
          End Do
          Do i = 2, n
            fvec(i) = fvec(i) + ruser(1)*x(i-1)
          End Do
          Do i = 1, n - 1
            fvec(i) = fvec(i) + ruser(4)*x(i+1)
          End Do
        Case Default
          Exit revcomm
        End Select

      End Do revcomm

      Write (nout,*) 'Final approximate solution'
      Write (nout,99999)(x(i),i=1,n)
99999 Format (1X,3F12.4)

    End Program c05qd_p0w_fe