







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Numerical programming often requires repeating the same calculations with differ- ent data and variables. Examples include having to integrate different functions or the same function over different intervals repeatedly. Having to recode the same chunk of fortran statement is wasteful of time and error prone as typos and bugs can be introduced in the process, moreover, the time we have invested in validating a specific piece of code would have to be duplicated again and again. Most pro- gramming languages provide a mechanism to avoid these repetitions and pitfalls. In FORTRAN this is done simply and elegantly by turning algorithmically related code segments into subprograms or procedures. There are many kinds of sub- programs in FORTRAN: subroutines, functions, and BLOCK DATA subprograms. Moreover, subroutines and functions can come in two flavors, internal and exter- nal. The func function already encountered in the trapezoidal rule integration is one example of an internal procedure. Subprograms are essential to build complex software as it allows programmers to think of their code in terms of algorithmic units and permits some degree of code abstraction. The benefits is that the de- velopment and validation of code can be done flexibly and in manageable units. Validated software can also be reused without having to worry repeatedly about its correctness.
The example of trapezoidal integration will be used again to illustrate the use of external procedures; the code for an adaptive trapezoidal integration is listed in ??. Clearly one can see a division of tasks among the different portions of the code. More specifically, one can distinguish the following phases in the program:
1 program trap 2 implicit none 3 integer :: N! number of intervals 4 real :: a,b! interval extrema 5 integer :: maxiteration! maximum number of iterations allowed 6 integer :: i, iteration! counters 7 real :: dx, Ans, xi, error, Ansold, tolerance
8 print ,’Enter a, b,tolerance, initial N, maxiteration’ 9 read , a,b, tolerance, N, maxiteration 10 do iteration = 1,maxiteration! iteration count 11 dx = (b-a)/real(N)! grid size 12 Ans = 0.5( myfunc(a) + myfunc(b) )! Evaluate function at a and b 13 do i = 1,N- 14 xi = idx + a 15 Ans = Ans + myfunc(xi) 16 enddo 17 Ans = Ans * dx! Integral estimate with N points 18 if (iteration > 1) then! one iteration before check 19 error = abs(Ans - Ansold) 20 if (error < tolerance) then! absolute error 21 exit! converged, exit loop 22 else! if not converged do following 23 N = 2*N! double number of intervals 24 Ansold = Ans! store old answer 25 endif 26 else 27 error = 0. 28 endif 29 print *, N, Ans, error 30 enddo 31 print *, N, Ans, error! print final answer
32 stop 33 contains 34 real function myfunc(x) 35 implicit none 36 real, intent(in) :: x 37 myfunc = x** 38 return 39 end function myfunc 40 end program trap
Figure 5.1: Code for adaptive trapezoidal integration
1 program trap 2 implicit none 3 integer :: N! number of intervals 4 real :: a,b! interval extrema 5 integer :: maxiteration! maximum number of iterations allowed 6 integer :: i, iteration! counters 7 real :: dx, Ans, xi, error, Ansold, tolerance 8 9 print *,’Enter a, b,tolerance, initial N, maxiteration’ 10 read , a,b, tolerance, N, maxiteration 11 Ansold = Trapezoid(a,b,N)! first estimate of integral 12 do iteration = 2,maxiteration! iteration count 13 N = 2N! double number of intervals 14 Ans = Trapezoid(a,b,N)! new estimate of integral 15 error = abs(Ans - Ansold)! absolute error 16 if (error < tolerance) then 17 exit! converged, exit loop 18 else 19 Ansold = Ans! save old answer if not converged 20 endif 21 print *, N, Ans, error! monitor adaptation progress 22 enddo 23 print , N, Ans, error! print final answer 24 25 stop 26 contains 27 28!*********************************************************************** 29! Numerical integration via trapezoidal rule 30!*********************************************************************** 31 real function Trapezoid(a,b,N) 32 implicit none 33 integer, intent(in) :: N 34 real, intent(in) :: a,b 35 integer :: i 36 real :: x,dx, res 37 dx = (b-a)/real(N) 38 res = 0.5 * (myfunc(a)+myfunc(b)) 39 do i = 1,N- 40 x = idx + a 41 res = res + myfunc(x) 42 enddo 43 Trapezoid = dx * res 44 return 45 end function Trapezoid
program numinteg implicit none integer :: N,maxiteration real :: a,b,ainteg, tolerance call Input(a,b,tolerance,N,maxiteration) call AdaptTrapezoid(ainteg,a,b,tolerlance,N,maxiteration) print ,’Integral = ’, ainteg stop contains! the functions Trapezoid and myfunc should go below here !*********************************************************************** ! Adaptive integration !*********************************************************************** subroutine AdaptTrapezoid(ainteg,a,b,tolerance,N,maxiteration) implicit none integer, intent(inout) :: N, maxiteration real, intent(in) :: a,b, tolerance real, intent(out) :: ainteg integer :: iteration real :: Ans, Ansold,err Ansold = Trapezoid(a,b,N)! first estimate of integral do iteration = 2,maxiteration! iteration count N = 2N! double number of intervals Ans = Trapezoid(a,b,N)! new estimate of integral error = abs(Ans - Ansold)! absolute error if (error < tolerance) then exit! converged, exit loop else Ansold = Ans! save old answer if not converged endif print *, N, Ans, error! monitor adaptation progress enddo return end subroutine AdaptTrapezoid end program numinteg !*********************************************************************** ! Input parameters !*********************************************************************** subroutine Input(a,b,tolerance,N,maxiteration) implicit none integer, intent(out) :: N, maxiteration! number of subinterval real, intent(out) :: a,b, tolerance! interval print *,’Enter a, b,tolerance, initial N, maxiteration’ read *, a,b, tolerance, N, maxiteration return end subroutine Input
and will not be changed by the routine, these are given the intent(in) at- tribute. Others have no value upon entry to the subroutine, but their value is assigned upon exist; they are given the intent(out) attribute. Finally some arguments, have a value upon entry that is modified in the course of the subroutine execution, these are given the intent(inout) attribute. The intent attribute is not part of classical FORTRAN, but is extremely useful in documenting the code by immediately telling the programmer what vari- ables are modified. Furthermore, declaring the attribute allows the compiler to first check and alert the programmer if a value is changed inadvertantly, and second to perform some optimization.
How are arguments transferred from the invoking subroutine to the called sub- routine? One could imagine that a subroutine copies actual arguments into its dummy arguments at invocation, performs the calculations, and then the output arguments are copied back after the return. That would actually be a waste of memory and CPU, both precious commodities in the early days of computing.
FORTRAN uses instead what is known as call by reference or call by name because what is passed to the subroutine is not the value of the actual argument but its memory address. Subprograms manipulates the actual parameters directly by addressing the memory location where they are stored. Address calculation takes place entirely behind the scenes and memory locations are not directly avail- able to the FORTRAN programmer. So if a subrprogram changes the value of a dummy argument, the value of the actual argument gets changed immediately. For this reason, passing arguments that have the same name can lead to surprising results if their values are changed and can be potentially dangerous. This is called aliasing of arguments.
Function subprograms are very similar to subprograms but there are some impor- tant differences.
module trapez contains !*********************************************************************** ! Adaptive integration !*********************************************************************** subroutine AdaptTrapezoid(ainteg,a,b,tolerance,N,maxiteration) implicit none integer, intent(inout) :: N, maxiteration real, intent(in) :: a,b, tolerance real, intent(out) :: ainteg integer :: iteration real :: Ans, Ansold,err Ansold = Trapezoid(a,b,N)! first estimate of integral do iteration = 2,maxiteration! iteration count N = 2*N! double number of intervals Ans = Trapezoid(a,b,N)! new estimate of integral error = abs(Ans - Ansold)! absolute error if (error < tolerance) then exit! converged, exit loop else Ansold = Ans! save old answer if not converged endif print , N, Ans, error! monitor adaptation progress enddo return end subroutine AdaptTrapezoid !*********************************************************************** ! Numerical integration via trapezoidal rule !*********************************************************************** real function Trapezoid(a,b,N) implicit none integer, intent(in) :: N real, intent(in) :: a,b integer :: i real :: x,dx, res dx = (b-a)/real(N) res = 0.5 * (myfunc(a)+myfunc(b)) do i = 1,N- x = idx + a res = res + myfunc(x) enddo Trapezoid = dx * res return end function Trapezoid end module trapez
program numinteg use trapez implicit none integer :: N,maxiteration real :: a,b,ainteg, tolerance call Input(a,b,tolerance,N,maxiteration) call AdaptTrapezoid(ainteg,a,b,tolerlance,N,maxiteration) print *,’Integral = ’, ainteg stop contains! the functions Trapezoid and myfunc should go below here . . .
Figure 5.5: Usage of a module .
??, the corresponding code that uses the module is shown in ??. Notice that the main program has the statement use trapez to instruct the compiler to associate the subroutine AdaptTrapezoid with the one declared within the module. The module can be in a separate file or within the same file as the main program. In either cases, the use requires that the module trapez be compiled prior to the main program. Hence if it is included in the file containing the main program, it must precede it. The compiler can hence process and produce the information that the module need provide the main program with.
Fortran by default does not permit functions of subroutines to call themselves either directly or indirectly. However, complex algorithms can often be cast elegantly in terms of recursive calls, that is the algorithm divides the steps into subtasks that are identical by require different data. In that sense recursive procedures resemble do-loops by are much more powerful. They are also more expensive as a procedure call, and as local variable must be created for each instance the procedure is called. Let us revisit the example of trapezoidal integration. Our adaptive procedure doubled the number of points uniformely, regardless of the shape of the function. This can be wasteful in places where the function behaves mostly like a straight line since the trapezoidal error is already small there. The error analysis reveals that the errors are largest in regions where the curvature of the function is large. A more astute adaptation strategy would resolve the high curvature regions, only sparse sampling of the function would be necessary in regions where it behaves
! Numerical integration via trapezoidal rule !*********************************************************************** recursive real function TrapezoidRec(a,b,tolerance) implicit none real, intent(in) :: a,b,tolerance real :: xm,dx, est1, est2, error, myfunc dx = (b-a)! interval width xm = 0.5(a+b)! interval midpoint est1 = 0.5 * (myfunc(a)+myfunc(b)) * dx! one-trapeze estimate est2 = 0.5 * (dx * myfunc(xm) + est1)! two-trapeze estimate error = abs(est2 - est1) if (error > 3.0tolerance) then est1 = TrapezoidRec(a,xm,0.5*tolerance) print , xm est2 = TrapezoidRec(xm,b,0.5tolerance) TrapezoidRec = est1 + est else TrapezoidRec = est endif return end function TrapezoidRec
Figure 5.6: Recursive trapezoidal integration
Cell numbers
x
Figure 5.7: Quadrature points for the recursive trapezoidal rule, the grid spacing for these boxes is shown in the right hand figure.