You are on page 1of 16

PHYS-4007/5007: Computational Physics

Course Lecture Notes


Section II

Dr. Donald G. Luttermoser


East Tennessee State University

Version 4.1
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. How To Select a Programming Language

A. Which is the Best Programming Language for Your Work?

1. Selection of a programming language for a given task can be a


daunting task. One must weight the availability of the language,
the functions it is capable of, and the speed and debugging ca-
pabilities offered by the compiler.
a) Different fields of study typically have their favorite pro-
gramming language.

b) Many mathematicians use Mathematica, Maple, and Math-


lab.

c) In physics and astronomy, most of the large codes are


written in Fortran 77, with the remaining small percentage
written in either the newer Fortran 90 or C (very few are
written in C++).

d) Astronomers who use a lot of NASA space data typically


use the Interactive Data Language (IDL) for their work.

e) Since we don’t have time to cover each and every pro-


gramming language on the market, we will intercompare
the three most commonly used in physics and astronomy:
Fortran 77, C, and IDL.
i) The details of Fortran 77 and an overview of For-
tran 90/95 can be found in Appendix A of these
notes.

ii) The details of C and an overview of C++ can be


found in Appendix B.
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.

2. 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).

3. 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–3

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.0d0
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, x1
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
II–4 PHYS-4007/5007: Computational Physics

Table II–1: (cont.) Analogous Elements in Fortran, C, and IDL

Fortran C IDL

Control Structure: for


do 2 k=1,kmax,1 for (k=1;k<=kmax;k++) for k=0,kmax-1,1 do begin
term = r∗term { term = r∗term; term = r∗term
2 continue sum = sum+term; } endfor

Switch
goto (1,2), choice switch (choice) { case choice of
1 series = first case 1: 1: series = first
2 series = second series = first; 2: series = second
break; else:
case 2: endcase
series = second;
break;
}

B. The Fortran Programming Language.

1. Fortran was first developed in 1957 by IBM and was the first
high-level programming language.
a) Its name is derived from “FORmula TRANslation.”

b) Fortran has evolved considerably since 1957 =⇒ Fortran


I → Fortran II → Fortran III → Fortran 66 (Fortran IV)
→ Fortran 77 (Fortran V) → Fortran 90 → Fortran 95.

c) Fortran is a sequential programming language — there


is a logical flow to the coding: the first line of the code
is operated upon first, the 2nd line, second, through the
last line, last.

d) Most large number-crunching codes in science are written


in Fortran 77 which came on the market in 1978.
Donald G. Luttermoser, ETSU II–5

2. 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

3. 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:
Donald G. Luttermoser, ETSU II–7

a) Initially there are one of two things you need to do to get


a Fortran code running on a PC with MS Windows. If this
is the first time trying to write, compile, and run a code,
select the “File” menu item on the toolbar, then follow
the next recipe:

i) Select “New” which will bring up a new GUI.

ii) In this new GUI, select QuickWin Application from


the “Projects” folder.

iii) Enter the project name (choose whatever name


you feel is appropriate — do not put spaces in the
name), make sure the Create a new Workspace but-
ton has been selected, and finally, pick a location
for the workspace directory that is unique to you
(make one with the Create New Folder button).

iv) Select “New” from the “File” menu in the upper


left of the main GUI if your Fortran code has not
been written yet and select “File” from the menu
items. If you are importing a file which was created
somewhere else, select “Open” instead of “New.”

v) This brings up an editor in which you can type in


your code. Once done, select “Save As ...” from the
“File” menu item and save your file to an appro-
priate filename (usually the name of the Workspace
name that you selected above). If your file had
previously been saved to the file name that you
selected, just select the “Save” menu item under
“File.”
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–9

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,
100) [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 <return> 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 ‘<return> 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.
II–10 PHYS-4007/5007: Computational Physics

b) Let’s say we wish to create a code called atlas.f (or we


already had one by that name). Issue the command (at
the Unix prompt):
emacs atlas.f

c) This will bring up the emacs editor window and start writ-
ing your code. When done, click the “Save” button (fol-
lowed by the “Exit” button if you don’t need to make any
more modifications). Let’s say that we edit a second file
which contains some operating system specific command
(like the GETNODE() function that is available on some
Fortran compilers) called atlasunix.f.

2. The Linux operating system uses the GNU Fortran compiler called
g77. Read the ‘man’ pages on fester for a listing of compiler
options.

3. Compiling and linking the code are performed with one command
(again at the Unix prompt):
g77 –o atexe –W atlas.f atlasunix.f
a) Here the “–o” flag tells the linking software to save the
executable code in a file called atexe (if ‘–o’ was not in-
cluded, the executable would be saved in a file named
a.out).

b) The ‘–W’ (capital ‘W’) tells the compiler and linker to


issue extra warnings such as floating point overflows (and
underflows) during operation (see Appendix A).

c) Note that GNU Fortran does allow some Fortran 90 con-


structs when using the –ff90 option switch and VAX For-
tran constructs when using the –fvxt option switch. See
the ‘man’ pages for further information.
Donald G. Luttermoser, ETSU II–11

4. 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.

3. 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.

4. Many of you are already familiar with the object-oriented pro-


gramming language known as C++. The University has a C++
Donald G. Luttermoser, ETSU II–13

compiler which you are free to use. They do not have a C com-
piler. As such, if you wish to program in C, you will have to carry
out your calculations on the Linux workststion (see below).

F. The Origin and History of the C Programming Language.

1. C is a member of the ALGOL family of programming languages.

2. Ancestry: ALGOL 60, CPL, BCPL, B, and ALGOL 68.

3. CPL was developed at Cambridge University around 1963, for


compiler writing.

4. BCPL was derived from CPL as a simple systems language — by


J. Richards at Cambridge (1967).

5. B (derived from BCPL) — Bell Labs (AT& T) late 1960s, for


developing the Unix operating system, (incidentally, for a PDP-
7 computer, which had 4K 18-bit words! ); developed by Ken
Thompson (1970).

6. C (1972) by Thompson & Dennis Ritchie.

7. Successor C++, Stroustrup (AT& T) 1986 – superset, object-


oriented, stronger type checking; it should be noted that the
development of C++ influenced ANSI C.

8. ANSI C (1988).

9. 1991 ISO C.

10. 1994 ISO C Amendment 1.


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.

2. 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.

You might also like