! Program Example from "Essential Fortran 90 & 95" by Loren P. Meissner
! Copyright 1996. Copying for sale requires permission from the author.
! Otherwise, distribution is permitted if these three lines are included.

! Example 4.12. Compare positive and negative exponential power series.
  program E12
    implicit none
    integer, parameter :: P = 12, K = selected_real_kind( P )
    integer :: N
    real (kind = K) :: Term, Sum_1, Sum_2, X, T_Sign
! start program E12
    do
      write (unit = *, fmt = *) " Please enter X "
      read (unit = *, fmt = *) X
      if (abs( X ) <= 4.0_K * spacing( 1.0_K )) then
        exit  ! Stop if X is close to 0.
      end if
  ! Initialize power series for new value of X:
      Sum_1 = 0.0_K
      Sum_2 = 0.0_K
      Term = 1.0_K
      T_Sign = 1.0_K
      do N = 0, 100  ! Exit when Term is small or after Term is 100.
        Sum_1 = Sum_1 + Term  ! E^X power series
        Sum_2 = Sum_2 + Term * T_Sign  ! E^(-X) power series
        if (abs( Term ) < spacing( 1.0_K )) then
          exit
        end if
        Term = Term * X / real( N + 1, K )
        T_Sign = - T_Sign
      end do
      write (unit = *, fmt = *) " X:                ", real( X )
      write (unit = *, fmt = *) " Exp Intrinsic:    ", exp( X )
      write (unit = *, fmt = *) " E^X power series: ", Sum_1
      write (unit = *, fmt = *) " 1 / E^(-X):       ", 1.0_K / Sum_2
    end do
    stop
  end program E12
