Course Lecture Notes for Computational Physics at East Tennessee State University - Prof. , Study notes of Physics

These are class notes for the course phys-4007/5007: computational physics i taught by dr. Donald luttermoser at east tennessee state university, including code examples and explanations in c programming language.

Typology: Study notes

Pre 2010

Uploaded on 08/13/2009

koofers-user-5ft
koofers-user-5ft 🇺🇸

10 documents

1 / 44

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
PHYS-4007/5007: Computational Physics
Course Lecture Notes
Appendix B
Dr. Donald G. Luttermoser
East Tennessee State University
Version 4.1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c

Partial preview of the text

Download Course Lecture Notes for Computational Physics at East Tennessee State University - Prof. and more Study notes Physics in PDF only on Docsity!

PHYS-4007/5007: Computational Physics

Course Lecture Notes

Appendix B

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 I taught by Dr. Donald Luttermoser at East Tennessee State University.

Appendix B–2 PHYS-4007/5007: Computational Physics

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.

f) Program layout is very important; I suggest two spaces indentation for each block; I suggest that you avoid tabs

  • certainly, avoid having the program pressed up against the right margin, with all the white space on the left hand side.

g) The #include <stdio.h> is a directive to the C preproces- sor to include the contents of a file called stdio.h; stdio.h contrains declarations of STanDard Input-Output func- tions; include means that the full contents of the file stdio.h are inserted where the #include directive appears; only then is the program passed to the C-compiler proper. #include is C’s way of importing.

h) In the definition of a function, () encloses the argument list; in this case main expects no arguments; (void) explic- itly denotes has no arguments.

Donald G. Luttermoser, ETSU Appendix B–

i) { ... } enclose the statements in a function.

j) printf is a library function for printing output on the users screen — in this case the string of characters between quotes; \n is C notation for newline; printf will not insert a newline by itself.

k) \n represents a single character — neccessary, since typing the key in the middle of a string is not really practical! Other control characters are: \t = tab, \a = alert bell, \” = double quote, \r = carriage return, \ = backslash itself!

l) return 0; in C, programs can return values to the operating system; in UNIX, ’0’ signifies that the program terminated normally; other values indicate error conditions. This is useful if you intend putting your program in a UNIX shell script; likewise DOS ’.bat’ files.

B. Variables and Arithmetic.

  1. Convert degrees Fahrenheit to degrees Celsius:

TC =

(TF − 32).

Then, print a list as follows: 0 - 20 - 40 4 60 15 300 148 /------------------------------------------------ ftoc.c - Fahr. to Celsius table j.g.c. 3/10/ Copied from K&R p. --------------------------------------------------/ #include <stdio.h> int main(void)

Donald G. Luttermoser, ETSU Appendix B–

i) Condition is tested.

ii) If condition is true — body is executed.

iii) Go back to 1.

iv) However, if condition is false — execution con- tinues at the statement following the loop.

  1. Note the textual layout style used: as mentioned earlier, my sug- gestion is to indent each block by 2 characters — the Kernighan & Ritchie (K&R) book on C (The C Programming Language — considered by many to be the C bible) use the next tab, but with that you very quickly get to the right-hand side of the page; on the other hand, we have to be able see what is part of a block and what isn’t.
  2. For me it is essential that the closing brace lines up with while.
  3. Integer arithmetic causes truncation: hence 5/9 → 0.
  4. printf:

a) Has multiple arguments; the first is always a string con- stant — then, this may contain codes (e.g., ’%d’) to say how subsequent arguments are to be printed.

b) %d: print the second argument as a decimal integer.

c) printf is not part of the C language — but it’s in the standard library, which is available with all C compilers.

d) Field widths can be specified, e.g., %6d.

e) Uses right justification, unless specified otherwise.

Appendix B–6 PHYS-4007/5007: Computational Physics

  1. In ftoc.c, we have a problem with integer arithmetic: not really satisfactory — truncation — e.g., 5/9 = 0! Therefore, we need a floating point version of ftoc.c: /------------------------------------------------ ftoc1.c - Fahr. to Celsius table, floating point version j.g.c. 3/10/ Copied from K&R p. --------------------------------------------------/ #include <stdio.h> int main(void) { float fahr, celsius; int lower, upper, step;

lower = 0; /* lower limit of table - fahr./ upper = 300; /upper limit/ step = 20; /step size*/ fahr = lower; while(fahr <= upper){ celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } return 0; }

  1. Dissection: a) Mixing of operands is allowed in C, e.g., fahr = lower; while(fahr <= upper); but this does not mean that there is no type checking; in the examples given, the ints are con- verted to floats before the operation is done. In general, you should be very careful with this feature. Actually, it might be better to make type conversion explicit, this can be done with a type cast, thus: fahr = (float)lower;

b) f conversion specification in printf: i) %3.0f: 3 characters wide, no decimal point, no fraction digits.

Appendix B–8 PHYS-4007/5007: Computational Physics

printf("%d %6.1f\n",fahr,(5.0/9.0)*(fahr-32)); } return 0; }

  1. Major differences: a) In printf(), celsius is replaced by a complex expression that evaluates to celsius; this should be nothing new to those who have used Fortran; the general rule is: A variable of some type can be replaced by an arbitrarily complicated expression that evaluates to a value of that type.

b) for statement and loop: There are three statements con- tained within the ’(.)’ in a for statement: i) fahr = 0: initialization.

ii) fahr <= 300: loop continuation control; evaluate the condition — if true execute the body — other- wise jump out.

iii) fahr = fahr + 20: increment; do this AFTER the first and subsequent loops — BEFORE evaluation of control condition.

iv) The for(...) body may be a single statement or a block { ... }.

D. Symbolic Constants and the Preprocessor.

  1. The general form of a symbolic definition is: #define <symbolic-name> <replacement-text>.

Donald G. Luttermoser, ETSU Appendix B–

  1. The C preprocessor replaces all occurrences of <symbolic-name> with <replacement-text> — just like an editor global-replace com- mand.
  2. Final version — ftoc3.c: /------------------------------------------------ ftoc3.c - Fahr. to Celsius table, demo of Symbolic constants j.g.c. 3/10/ Copied from K&R p. --------------------------------------------------/ #include <stdio.h>

#define LOWER 0 /lower limit of table/ #define UPPER 300 #define STEP 20 int main(void) { int fahr; float celsius; for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP){ celsius = (5.0/9.0) * (fahr-32); printf("%3d %6.1f\n", fahr, celsius); } return 0; }

  1. Dissection: a) The preprocessor is an extremely important part of C. When you compile a C program, two things happen: First, the preprocessor runs through the file, second, actual com- pilation. Therefore, in the example given above, all oc- currences of the string ”LOWER” get replaced with ”0”; the compiler never sees the ”LOWER”; and, LOWER is not a variable.

b) Adopt a convention to use upper-case for symbolic con- stants; be very careful what else you use upper case for.

Donald G. Luttermoser, ETSU Appendix B–

echoes it to the screen / terminal; immediately means BE- FORE it is presented to the reading program (see buffered below). (Incidentally, this means that the terminal, it- self, does not display the typed character — just what is echoed from the host computer.)

c) Buffered input. While the user is typing, the com- puter stores all the typed characters in a buffer (array) and presents the array (line) of characters to the reading program ONLY AFTER A CARRIAGE RETURN (En- ter) has been typed.

  1. Terminal input-output and I-O Redirection a) C (and UNIX) has a fairly unified view of text input- output. Reading from the keyboard is like reading from a file device called stdin. However, there are special stdin routines that hide that fact, e.g., getchar() below is exactly equivalent to getc(stdin). Likewise, putchar(c) is equiva- lent to putc(c, stdout), where stdout is the standard-output device, i.e., the screen.

b) Incidentally, putc(c, stdprn) is a handy way of writing to a PC printer, as is putc(c, stdaux) — to the auxiliary (com- munications) port, where stdprn is the standard printer device, and stdaux is the standard auxiliary device. BUT THESE ARE NOT STANDARD C / UNIX.

c) So, when we talk about file I-O below, we include ter- minal I/O. All the programs below can be tested using the terminal. (Note: z is EOF (end-of-file) for a keyboard).

Appendix B–12 PHYS-4007/5007: Computational Physics

d) If you want to test the programs using files, you can use input-output redirection. i) First, you must get the compiler to compile to an .exe file, say cio.exe.

ii) Second, create a text file, say test.dat. Then, en- ter at the Unix prompt cio < test.dat which tells cio to read from test.dat =⇒ the < redi- rects the program to read from the file instead of the keyboard.

iii) If you want to send the output to a file, say testout.dat, use cio < test.dat > testout.dat.

  1. File Copying. Make a program with the following algorithm: read a char while(char is not an eof char) output the char just read read a char /------------------------------------------------- cio1.c - copy input to output, version 1. j.g.c. 3/10/ copied from K&R p.16. -----------------------------------------------------/ #include <stdio.h> int main(void) { int c; c = getchar(); while(c != EOF){

Appendix B–14 PHYS-4007/5007: Computational Physics

  1. Character Counting. Objective: count the characters in the input stream, stop at EOF.

/------------------------------------------------ ctch1.c - counts input chars; version 1 j.g.c. 3/10/89. copied from K&R p.18. ---------------------------------------------------/ #include <stdio.h> int main(void) { long nc; nc=0; while(getchar() != EOF) ++nc; printf("%ld\n", nc); return 0; }

Dissection: a) ++ operator: increment by one; – –: decrement by one. Note: As single statements, ++nc and nc++ are equiva- lent, but give different values in expressions, e.g., int i, n; n = 6; i = ++n; /* POST-increment gives i == 7, and n == 7; the increment is done BEFORE the assignment / wheras, n = 6; i = n++; / POST-increment gives i == 6, and n == 7 */

b) long (integer) is at least 32 bits long.

c) %ld tells printf to expect a long.

Donald G. Luttermoser, ETSU Appendix B–

  1. Line Counting. /-----------------------------------------------/ #include <stdio.h> /* count lines in input/ int main(void) { int c, nl; nl = 0; while((c=getchar()) != EOF) if(c == ’\n’) ++nl; printf("%d\n", nl); return 0; } /--------------------------------------------------*/ Dissection: a) if statement: tests condition in (...) if true executes statement or group { ... } following, otherwise (false) skip them.

b) == means is-equal to. CAUTION: = in place of == can be syntactically correct and so not trapped by compiler — a nasty hard-to-find error results!

c) Character constants, e.g., ’\n’ represents an integer value equal to the value of the character in the machine’s charac- ter set; In ASCII: ’\n’ == 10 decimal; ’A’ == 65 decimal.

  1. Word Counting. Word = any sequence of chars that does not contain a white-space char. i.e., blank, tab, newline. /-----------------------------------------------------/ #include <stdio.h> #define IN 1 /inside a word/ #define OUT 0 /outside a word/ /* count words, lines and chars in input*/

Donald G. Luttermoser, ETSU Appendix B–

  1. Arrays. Below is a program to count the occurrences of each nu- meric digit, of white-spaces and of all other characters (together) — without using 12 named counters! /---------------------------------------------------/ #include <stdio.h> /counts digits, white-spaces, others/ int main(void) { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for(i=0; i<10; i++) ndigit[i] = 0; while((c=getchar()) != EOF) if(c>=’0’ && c<=’9’) ++ndigit[c-’0’]; else if(c==’ ’ || c==’\n’ || c==’\t’) ++nwhite; else ++nother; printf("digits ="); for(i=0; i<10; ++i) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); return 0; } Dissection: a) int ndigit[10]; an array of 10 ints.

b) The for( ... ) loops must go 0, 1, ... 9, since, in C, array subscripts must start at 0.

c) The test if( c>=’0’ && ... : && denotes logical AND.

d) c–’0’ assumes that ’0’,’1’...’9’ have consecutive, increasing values.

e) c–’0’ is an integer expression =⇒ it’s OK for a subscript.

Appendix B–18 PHYS-4007/5007: Computational Physics

f) if( condition1 ) statement else if( condition2 ) statement ........ else statement This is the model for a multiway decision; you can have any number of else if ( cond ) stmt groups between first if and final else; the final else catches anything that didn’t satisfy any of the previous condi- tions.

g) Indenting style: Again, please note that we don’t want to run off the right-hand edge of the paper.

F. Functions.

  1. We have already encountered functions that have been written for us, e.g., printf, getchar, putchar.
  2. Here is a program that reads ints and floats and does some arith- metic with them. We’ll use it as a case-study of many of the aspects of functions. /------------------------------------------- math1.c j.g.c. 6/1/ demo of functions -- in same file --------------------------------------------/ #include <stdio.h> int getInt(void) { int i;