Docsity

Lecture Notes on Computational Physics: A Comparison of Fortran 77, C, and IDL - Prof. Don, Study notes of Physics

Partial preview of the text

Download Lecture Notes on Computational Physics: A Comparison of Fortran 77, C, and IDL - Prof. Don and more Study notes Physics in PDF only on Docsity!

PHYS-4007/5007: Computational Physics

Course Lecture Notes

Section II

Dr. Donald G. Luttermoser East Tennessee State University

Version 4.

Abstract

These class notes are designed for use of the instructor and students of the course PHYS-4007/5007: Computational Physics taught by Dr. Donald Luttermoser at East Tennessee State University.

II–2 PHYS-4007/5007: Computational Physics

iii) The details of IDL can be found in the next sec- tion (i.e., §III) of these notes.

f) Any coding introduced in these notes will be written in ei- ther IDL or Fortran 77, hence Appendix A and §III should be studied carefully so you fully understand what is being written in these code segments.

  1. Most programming languages have analogous elements in their programming style, which can be reduced to 8 sections as shown in Table II-1 (partially lifted from Appendix A of your textbook).
  2. No matter which programming language you choose, you need to come up with a style and be consistent throughout the code. a) You do this not only to make it easier for other users to figure out what you are doing, it makes it easier on you when you go back to a code after you haven’t looked at in a long time.

b) Always have numerous comments throughout the code describing what is being done!

c) For my style, I use lower-case letters (except for the first letter of words at the beginning of a sentence) for com- ments and upper-case letters for the coding itself. (Though in Table II-1, I use lower-case letters for demonstration purposes only.)

d) Try to use a lot of subroutines (or procedures) and func- tions =⇒ make your code as modular as possible. (PAN- DORA has over 4500 subroutines in it!)

Donald G. Luttermoser, ETSU II–

Table II–1: Analogous Elements in Fortran, C, and IDL Fortran C IDL Program Structure program f main() (no main program structure) function f(x) double f(double x) function f, x subroutine f(x) void f(x) pro f, x Operations x∗∗y pow(x,y); x∧y x = y x = y; x = y do 2 k=1,kmax,1 for (k=1;k<=kmax;k++) for k=0,kmax-1,1 do do 2 k=kmax,1,-1 for (k=kmax;k>=1;k–) for k=kmax-1,0,-1 do Data Type Declarations real∗8 x, y double x, y; x = 0.0d0 & y = 0.0d integer i, j int i, j; i = 0 & j = 0 real∗8 y(100,100) double y [100] [100]; y = dblarr(100,100) integer ii(100,100) int ii [100] [100]; ii = intarr(100,100) data mn/0.0/ define mn 0.0; defsysv, ’ !mn’, 0.0, /read only character jan char jan; jan = ’ ’ (NULL string) Input and Output to Screen read(∗, ∗) x1 scanf(“%lf”, &x1); read, x write(∗, ∗) ’Enter radius:’ printf(“Enter radius:”); print, ’Enter radius:’ write(∗, ∗) ’radius = ’, radius printf(“radius = %f”, radius); print, ’radius = ’, radius Input and Output to Files FILE *fout; open(7,file=’x.dat’,status=’new’) out = fopen(“x.dat”, “w”); openw, 7, ’x,dat’ write(7,’(f10.2)’) Din fprintf(fout, “%lf”, Din); printf, 7, Din, format=’(f10.2)’ read(7,100) Din fscanf(fin, “%lf”, &Din); readf, 7, Din Control Structure: if if (den .eq. 0) then if (den == 0) { if den eq then begin write(∗, ∗) ’Trouble’ printf(“Trouble”); print, ’Trouble’ endif } endif Control Structure: if ... else if (den .eq. 0) then if (den == 0) if den eq then begin x = 0 { x = 0; } x = 0 else else endif else begin x = x1/den { x = x1/den; } x = x1/den endelse

Donald G. Luttermoser, ETSU II–

  1. Fortran has a number of features that make it useful to the sci- entific community:

a) Portability: Portability means that it is easy to move from one machine to another. While no large program can move from one machine to another totally without difficulty, problems are usually minor, provided the For- tran 77 standard has been strictly adhered to.

b) Availability: Fortran is probably more widely used than any other programming language in the academic com- munity. It is certainly the most widely used by scientists and engineers. Compilers are available for all machines, from micro to mainframe, likely to be encountered in a university.

c) Efficiency: Partly because of its simple, static use of store, and the un-complicated nature of its constructions, and partly because of a massive investment in compiler development, numerically intensive programs written in Fortran are generally faster than those in any other high- level language. The technique of optimization, by which a compiler alters the machine code it generates (without changing the end result!) to speed the calculation is more developed for Fortran than any other language.

d) Fortran Libraries: Very considerable effort has gone, over many years, into the production of libraries of rou- tines that may be called from Fortran programs. Chief amongst these are libraries of numerical-analysis routines (such as the very large NAG library) and routines to do graph plotting (such as the GINO, DI-3000, and UNIRAS libraries).

II–6 PHYS-4007/5007: Computational Physics

  1. Fortran is designed to be modular: a) One has a main program that drives the code and calls subroutines and functions.

b) A good Fortran code typically has a short main program which call many subroutines.

c) Subroutines and functions can call other subroutines and functions.

C. Running Fortran on the PCs.

  1. Some of you may have copied over the free-ware GNU Fortran 77 compiler. If you plan on using this software, read the readme.txt for information on installing and running this compiler (note that this ‘g77’ compiler must be ran from DOS mode). This package contains the SLATEC mathematical library which is similar to the LAPACK library (see Appendix A).
  2. For those of you running a Fortran 77/90 code from the PCs in Brown Hall, Digital Visual Fortran 5 has been installed on these machines. Simply double click on the appropriate menu item in the Start menu or the Developer Studio icon on the main screen.
  3. One then creates a Fortran code in the editor window and used the various buttons and pull-down menus to compile and run the code. You will have to retrieve the LAPACK or BLAS libraries from the netlib web site if you wish to use them. Then, use the ‘Help’ utility (search on “math library”) for instructions on using external libraries.
  4. To compile and run on a PC using Microsoft’s Development Studio version of Digital’s Visual Fortran, do the following tasks:

II–8 PHYS-4007/5007: Computational Physics

vi) In the main program, just after the first “PROGRAM” startement, include the the line USE DFLIB. Then after the declaration and common block statements, include the line IOLDCT = SETTEXTCOLORRGB(#00FFFFFF). (Take these lines out if you port your code to a Unix machine.)

vii) These two lines are needed in order for Microsoft Windows to bring up a “text window” and to change the text color to white so that you can read the lines output to this window with WRITE and PRINT statements.

b) If you have already set up your workspace and need to do further editing of your program, do the following:

i) Highlight the ”File” menu item on the toolbar, select the “Open Workspace” menu item. This will bring up a new GUI box.

ii) Find and select workspace name which will have a ‘.dsw’ as the file name suffix.

iii) The Fortran file (or files) you will need should already be present in this workspace. If not, open the needed file (or files) in the “File” menu item.

iv) Once you have made any editing changes, save the file, then select the “Build” item on the top menu bar and compile your files, first any supple- mentary Fortran files you have in the workspace, then the file that contains the main program sec-

Donald G. Luttermoser, ETSU II–

tion. Then go back to the “Build” item and se- lect “Build runname.exe” (where ‘runname’ is the name of the executable file that the compiler made).

c) Finally, to run your code, click the exclamation mark (“!”) above the editing window to run the code. A textbox window should appear that contains any output that you made to the terminal (usually a PRINT * or WRITE(6,

  1. [where ‘100’ is an arbitrary FORMAT statement ID]). i) Note that Microsoft Windows will immediate close the textbox window when the code finishes execut- ing.

ii) To prevent this from happening, issue the follow- ing commands just prior to the last executed line in your code (typically a STOP statement): PRINT , ’Hit to clear window.’ READ(, 110) ASK 110 FORMAT(A) where ASK needs to be defined as a CHARACTER variable and the ‘110’ number in the FORMAT state- ment would be some number that you have not yet used as an ID in that portion of your code (either the main program or a subroutine, wherever STOP is located). This way, Microsoft won’t close the window until you hit ‘ on your keyboard, hence allowing you to look at the output. D. Running Fortran on the Linux Workstation.

  1. To write a Fortran code under Linux, use the following recipe: a) Change directories to whatever subdirectory you want as your working directory.

Donald G. Luttermoser, ETSU II–

  1. Unlike the PC environment, whatever output is sent to the ter- minal screen will remain after the code finishes execution, so you don’t have to include the “READ” command that we described in the PC section of this section.

E. The C Programming Language.

  1. C, like Fortran 77, is referred to as a sequential programming language =⇒ the flow of the operations carried out by the com- puter line by line from the beginning of the main program to the end of it.
  2. Like Fortran, C is considered a higher-level language, but it has some lower-level language functionality =⇒ it can access the operating system much easier and more efficiently than Fortran 77/90. a) A “C” program = functions (executable code) + variables (data).

b) Every program must have a function called main, execu- tion starts there. main may call other functions. These functions can be taken from one of the following sources: i) As written by the programmer in the same file as main.

ii) As written by the programmer in separate file(s).

iii) Called from predefined libraries.

c) C has no concept of a Program as in Fortran, just func- tions.

d) The C view is that main is called by the operating system; the operating system may pass arguments to main, as well

II–12 PHYS-4007/5007: Computational Physics

as receive return values (e.g., return 0;); however, above, we choose to make main take no arguments – (void).

e) /* ... */ is a comment and is ignored by the compiler; the C standard says that comments cannot be nested. Also, comments must be terminated explicitly, i.e., new- line does not terminate them — this is a common source of compiler errors, and, for the unwary, can be very dif- ficult to trace. For your own sanity the header comment should include: i) Name of the program — to correspond to the file- name.

ii) Authors name — even if copied!

iii) Date.

iv) Brief indication of function and purpose of the program, e.g., assignment number, or project, and what it does.

  1. Appendix B of these course notes contains some details and a tutorial in programming with the C language. One thing to note is that C is not designed to be a “number-crunching” program- ming language. It has very limited mathematical operators and one must load additional math libraries at compile time to do any math beyond simple arithmetic (see below). If you are going to be crunching numbers, then Fortran is typically the code of choice.
  2. Many of you are already familiar with the object-oriented pro- gramming language known as C++. The University has a C++

II–14 PHYS-4007/5007: Computational Physics

G. Running C on the Linux Workstation.

  1. When compiling C code on fester, issue the command: gcc –o filename filename.c This will take the C code stored in filename.c, compile it and link it, storing the executable in file filename. a) The gcc command invokes the GNU C compiler.

b) Note that if the output option –o filename was not given, the executable would have been stored in file a.out.

c) However, your compilation may not go well. An ’Error’ indicates a serious flaw in the source code, which the com- piler cannot circumvent. In the event of any ’error’, the compiler can produce no usable object code.

d) ’Warning’, as the name suggests, is the compilers way of saying are you sure about this; examples are: variables defined but never used (fairly benign), functions called without any prototype / declaration present (definitely not benign – unless the types of the actual parameters are identical to the types of the formal parameters, you could be in for a nasty shock when the software executes).

e) I maintain that C compiler warnings must never be ig- nored, and insist that students heed this principle.

  1. If your C code uses functions from the standard C math library, issue the command on fester: gcc -o filename -lm filename.c where the ‘-lm’ tells the compiler to load the math library to the linker as well.