PHYSICS 580                                                             COMPUTATIONAL PHYSICS

 

Hints on organizing programs

 

There is no one right way. The three most important principles of organization are:

 

(1) Write short routines. The ideal is “one screen full,” that is about 25 lines, although in practice 50 lines is okay. This is not a rigorous rule, but if you find any routine (either main calling program or a subroutine or function) is getting longer than 50-60 lines you should consider if it could be broken up into smaller routines.

 

(2) Write lots of error traps.

 

(3) Document throroughly with comments.

 

While many comments are important, the most helpful are the following:

 

Detailed description of definition of input and output (e.g., do you assume the input is in meters? It is a nonnegative integer?) It is helpful when asking for input to specify this. For example, when calling Bode’s rule for integrals, remind the user that the number of points must be a multiple of 4. Notes on the form of the output are equally vital.

 

When commenting main program it is useful to supply at the beginning a list of all subroutines and non-intrinsic (not sin, cos, exp, etc.) functions called. For example:

 

C  program upsidedowncake

C

C  written 2/5/2005 by CWJ at SDSU

C  

C  this program inverts a cake via LU decomposition

C  see the algorithm in Numerical Desserts, Ch. 7

C   

C  subroutines called:

C               in cake_lib.f

C    get_ingredients:   asks for list of ingredients

C    check_measures:    check if amounts are compatible

C    turn_on_oven  :    sets oven temperature

C                in Lulib.f

C    LU_decomp     :    LU decomposition

C    LU_invert     :    LU inversion

C                in this file

C    serve_results :    serve final product to output file   

C

C  functions called:

C                in cake_lib.f

C    frostingthickness: (real) finds appropriate thickness

C

 

Note that I also commented where to find the routines, i.e., in what fortran file to find them. Believe me, this is extremely useful when working on long program with hundreds of routines and 20,000+ lines of code.

 

When commenting subroutines and functions, it is useful to specify the input and output, as well as any additional subroutines called:

 

C

C  subroutine check_measures(nservings,neggs,cupmilk,

C     cupflour,pinchsalt,errflag)

C

C  uses Child’s algorithm (see Numerical Desserts, p 155)

C  to check compatibility of amounts

C

C  input:

C    nservings: # of servings desired

C    neggs:  # of eggs

C    cupmilk: amount of milk in cups

C    cupflour: amount of flour in cups

C

C  output:

C    pinchsalt: amount of salt to add (in pinches)

C    errflag: logical flag, = .false. if everything okay

C                          = .true.  if incompatibility

C

C  subroutines called:

C                  in cake_lib.f

C    oz_to_cups:   converts ounces to cups

C

C  functions called:

C    NONE

C