!     Last change:  A    19 Oct 2004    9:59 pm
PROGRAM Mean_of_a_list_lab5_allocated
!
! Use a 1-D allocatable array and function call and formatted output
!
IMPLICIT NONE
INTEGER, PARAMETER :: MaxInteration = 99
INTEGER :: i, NumEndInteration
REAL(KIND = 8) :: Root
REAL(KIND = 8), DIMENSION(0:MaxInteration) :: X, Absolute, ErrorRatio

OPEN (1,file = 'LAB5.dat', status = 'REPLACE')

WRITE (*,*) "Input first interation: "
READ (*,*) X(0)

IF (X(0) < 0) THEN
   Root = -2.0D0
ELSE
   Root = 1.0D0
END IF

Absolute(0) = ABS( ( X(0) - Root ))
ErrorRatio(0) = 0

DO i = 1, MaxInteration
   X(i) = X(i-1) - ( F(X(i-1)) / DF(X(i-1)) )
   Absolute(i) = ABS( ( X(i) - Root ))
   ErrorRatio(i) = Absolute(i) / Absolute(i-1)**2

   IF ( ABS( X(i) - X(i-1) ) < .00000000000001 ) THEN
      NumEndInteration = i
      EXIT
   END IF
END DO

DO i = 0, NumEndInteration
   WRITE(*,'(1X, A, I2, A, F12.10, A, F12.10, A, F12.10)')"Interation ",i," is ",X(i)," Abs Error ",Absolute(i),"  Ratio is ",ErrorRatio(i)
   WRITE(1,'(1X, A, I2, A, F12.10, A, F12.10, A, F12.10)')"Interation ",i," is ",X(i)," Abs Error ",Absolute(i),"  Ratio is ",ErrorRatio(i)
END DO

CLOSE (1)
STOP
CONTAINS


FUNCTION F(X)

IMPLICIT NONE
REAL(KIND = 8), INTENT (IN) :: X
REAL(KIND = 8) :: F

F = X**4 + 5.0D0*X**3 + 6.0D0*X**2 - 4.0D0*X - 8.0D0

RETURN
END FUNCTION F

FUNCTION DF(X)

IMPLICIT NONE
REAL(KIND = 8), INTENT (IN) :: X
REAL(KIND = 8) :: DF

DF = 4.0D0*X**3 + 15.0D0*X**2 + 12.0D0*X - 4.0D0

RETURN
END FUNCTION DF

END PROGRAM Mean_of_a_list_lab5_allocated
