2.4 Programming Examples on Loss of Precision and Round-offErrors 29
IMPLICITNONE
REAL(DP) :: x, term, final_sum
INTEGER:: n, loop_over_x
! loop over x-values
DOloop_over_x=0, 100, 10
x=loop_over_x
! initialize the EXP sum
final_sum= 0.0_dp; term = 1.0_dp; n = 0
DOWHILE( ABS(term) > truncation)
term = ((-1.0_dp)**n)*(x**n)/ factorial(n)
final_sum=final_sum+term
n=n+1
ENDDO
! write the argument x, the exact value, the computed value and n
WRITE(*,*) x ,EXP(-x), final_sum, n
ENDDO
END PROGRAMexp_prog
TheMODULEdeclaration in Fortran allows one to place functions like the one which calculates
the factorials. Note also the usage of the moduleconstantswhere we define double and
complex variables. If one wishes to switch to another precision, one just needs to change
the declaration in one part of the program only. This hinderspossible errors which arise if
one has to change variable declarations in every function and subroutine. In addition we
have defined a global variabletruncationwhich is accessible to all functions which have the
USE constantsdeclaration. These declarations have to come before any variable declara-
tions andIMPLICIT NONEstatement.
http://folk.uio.no/mhjensen/compphys/programs/chapter02/Fortran/program5.f90
! In this module you can define for example global constants
MODULEconstants
! definition of variables for double precisions and complexvariables
INTEGER,PARAMETER:: dp =KIND(1.0D0)
INTEGER,PARAMETER:: dpc =KIND((1.0D0,1.0D0))
! Global Truncation parameter
REAL(DP),PARAMETER,PUBLIC:: truncation=1.0E-10
END MODULEconstants
PROGRAMimproved_exp
USEconstants
IMPLICITNONE
REAL(dp) :: x, term, final_sum
INTEGER:: n, loop_over_x
! loop over x-values, no floats as loop variables
DOloop_over_x=0, 100, 10
x=loop_over_x
! initialize the EXP sum
final_sum=1.0 ; term=1.0 ; n = 1
DOWHILE( ABS(term) > truncation)
term = -termx/FLOAT(n)
final_sum=final_sum+term
n=n+1
ENDDO
! write the argument x, the exact value, the computed value and n
WRITE(,*) x ,EXP(-x), final_sum, n
ENDDO
END PROGRAMimproved_exp