All posts by admin

Fortran: Lesson 2

Lesson topics


View Demos
# 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10
Download Demos
# 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10

We look at more of the commonly used features and commands of Fortran.

Logical Expressions

A logical expression is a relation between variables or expressions that can have a value of TRUE or FALSE. Such expressions are used in "if Ö then" constructions and in loops, when testing whether to execute certain steps of a program. Relations and connectives appearing in logical expressions are listed in the following table; you will see how some of these are used in later examples.

Relation/Connective   Meaning
.lt. less than
.gt. greater than
.le. less than or equal to
.ge. greater than or equal to
.eq. equals
.ne. not equal to
.and. and
.or. or
.not. not
.xor. "exclusive" or (i.e., only one is true)
.eqv. equivalent (i.e., same truth values)
.neqv. not equivalent

If ... Then ... Else Constructions

"If … Then … Else" constructions in Fortran are pretty much like those in Basic, with but a few minor modifications. First, instead of using in the tests symbols like "=", "<", ">=", etc., as in Basic, you must use the abbreviations in the preceding table. Also, tests must be enclosed in parentheses, and "else if" may be two words. Here are several examples:

  1. if (x .gt. 0) print *, "x is positive"
  2. if (x .ge. y .and. x .ge. z) go to 40
  3. 											if (x .ge. 0) then
    												y = sqrt(x)
    												print *, y, " squared = ", x
    											end if
  4. 											if (x .ge. 0) then
    												y = sqrt(x)
    												print *, y, " squared = ", x
    											else
    												print *, "x has no square root"
    											end if
  5. 											if (x .ge. 0) then
    												print *, "x is positive"
    												y = sqrt(x)
    											else if (x .lt. 0) then
    												print *, "x is negative"
    												go to 60
    											else if (x .eq. 0) then
    												print *, "x is zero"
    												y = 0
    											end if

Observe that, as in examples 1) and 2), the one-line "if" statement does not use "then". Moreover, "else" appears on a line by itself, while "else if" shares the line with the test condition and "then".

Stop

A stop statement stops the execution of a program. For instance, the sequence of statements below terminates the program whenever n is less than zero:

									if (n .lt. 0) then
										print *, "Error - your age cannot be negative!"
										stop
									end if

Do not confuse stop and end. Use end only as the very last statement in the program, and use stop only to terminate the program before this last statement. Violating these rules will fatally confuse the compiler - it regards an end statement as the program's physical end.

Labels and Go To

Labels and the "go to" statement work as in Basic, except that a label must be a number, and it must be typed in columns 2-5. Here is an example of a go to command directing the action to a labeled statement:

									if (x .lt. 0) go to 10
									print *, "The square root of x is ", sqrt(x)
									stop
								10	print *, "x is negative and has no square root"

Character Variables

A character variable is analogous to a string variable in Basic. A character variable must be declared at the beginning of the program, and attached to it in the declaration must be a number following an asterisk "*"; this number indicates the maximum number of symbols in the string. For example, the declaration statement
character name*20, ans*1

indicates that "name" is a character variable holding no more than 20 symbols, while "ans" is a character variable holding only one symbol.

A string in Fortran may be enclosed in either double quotes, as in "hello", or in single quotes, as in 'goodbye'.

Do Loops

"For … Next" loops in Basic become "Do Loops" in Fortran. Such a loop begins with a do statement, and ends with either end do, or a labeled continue statement. Here are two loops that add the squares of the integers from 1 to 10:

										sum = 0
										do i = 1, 10
											sum = sum + i ** 2
										end do
										print *, "The sum is", sum
									sum = 0
									do 5 i = 1, 10
									sum = sum + i ** 2
								5	continue
									print *, "The sum is", sum

The end do and continue statements serve only to identify the end of the loop. The limits of the loop may be variables as well as numbers (e.g.: do i = m, n). As in Basic you may indicate a step size, which can be positive or negative. For example, the statement

do i = 1, 9, 2
specifies that the loop variable i run over the odd numbers 1, 3, 5, 7, 9.
Loops can be nested, and nested loops can end on the same continue statement (but not on the same end do statement). Here are two instances of nested loops assigning the entries of a 10 x 10 matrix:
										do i = 1, 10
											do j = 1, 10
												a(i,j) = i + j
											end do
										end do
									do 5 i = 1, 10
									do 5 j = 1, 10
									a(i,j) = i + j
								5	continue

Fortran: Lesson 1

Lesson topics


View Demos
# 1
Download Demos
# 1

Introduction

Fortran is one of the oldest programming languages devised, but it is also still one of the most popular, especially among engineers and applied scientists. It was developed in the 1950's at IBM. Part of the reason for Fortran's durability is that it is particularly well-suited for mathematical programming; moreover, there are millions of useful programs written in Fortran, created at considerable time and expense, and understandably people are reluctant to trash these old programs and switch to a new programming language.

The name Fortran originally referred to "Formula Translation", but it has long since taken on its own meaning. There are several versions of Fortran around, among them Fortran 77, Fortran 90, and Fortran 95. (The number denotes the year of introduction.) Fortran 77 is probably still the most used, and it is the version installed on UHUNIX and in the UH math lab. Even though this semester we have thus far studied Basic, at the same time we have studied Fortran, because commands and procedures are very similar in the two languages. Moving from QuickBasic to Fortran is more a matter of change of terminology than anything else.

Editing Fortran

Unlike in Basic, a Fortran program is not typed in a "Fortran window". Instead, a program is typed and saved with an editor (i.e., a word processor), and the program is then turned into an executable file by a Fortran compiler. To begin the process of creating a Fortran program in the math lab, you must open an editor. It is preferable to use a simple editor - such as Notepad or the DOS editor - because fancy word processors might add extraneous formatting notation that will hang up Fortran.

A most peculiar feature of Fortran 77 is its line structure, which is a carryover from the old days when programs were typed on punch cards. A punch card had 80 columns, and so does a line of Fortran code. A "c" in column 1 indicates a comment (similar to REM in Basic). Columns 2-5 (usually left blank) are reserved for line numbers. Column 6 is used only to indicate a continuation of a line too long to fit on the card. Columns 7-72 contain the instructions of the program. Columns 73-80 were originally used for numbering the punch cards, but are rarely used nowadays - leave them blank and the compiler will ignore them.

Fortran is case insensitive - that is, it does not distinguish between capital and small letters. Thus x and X refer to the same variable. Many programmers for simplicity use all small letters, but you may do as you like. Also, after column six Fortran does not recognize spaces (except for spaces inside quotations as in print statements). In general, spaces are mostly for the purpose of making code more readable by humans. When you type a Fortran program with an editor, make certain the editor indents more than six spaces; then if you begin every line with an indent you do not have to worry about counting six spaces at the beginnings of lines.

Let us go through the steps of editing, compiling, and running a short program. First open Notepad under Windows, or type "edit" (and return) under a DOS prompt to open the DOS editor. (When you double-click the Fortran icon on a math lab computer, you get a DOS prompt.) Beginning each line with an indent (except for the fourth line, where the "c" must be placed in the first column), type the program exhibited below; the program computes the area of a circle of radius r, as input by the user. The resulting file that you save is called the source file for the program.

									program circlearea
									real r, area, pi
									parameter (pi = 3.14159)
								c	This program computes the area of a circle.
									print *, "What is the radius?"
									read *, r
									area = pi * r ** 2
									print *, "The area is", area
									print *, "Bye!"
									end

The first statement above gives the program name, the second declares that "r", "area", and "pi" will be single precision real quantities, and the third announces that pi has the value 3.14159. The fourth statement, beginning with "c" in column 1, is a comment describing what the program does; such comments are for the benefit of the programmer and are ignored by Fortran. The fifth statement prompts the user for the radius of the circle, and the sixth accepts this input. The seventh statement computes the area and the eighth informs the user of this area. Finally, the last two statements bid goodbye and terminate the program.

The name for a source file in Fortran must end with the extension ".f" before the compiler recognizes it. After you have typed the above program, save the file as area.f. (If you type the file in Notepad, include the whole name in quotes when you save it, as otherwise the extension .txt will be added to the name.) The file will be saved to your h directory in the math lab. Under a DOS prompt you can view the files in this directory by typing dir and enter; under Windows you can double-click "My Computer" and then the icon for the h drive.

Compiling

After you have created and saved a source file, you next must compile this file. Open a Fortran window and enter

g77 name.f

where in place of name you insert the name of your source file. (If the source file resides in a directory different from that of the Fortran program, you will have to include also the directory path of the file.) To compile the file of our example above, in the math computer lab you just enter g77 area.f.

If your program has mistakes (which usually happens on the first attempt at compiling), instead of a compiled file you will get Fortran error messages pointing out problems. Some of these messages can be hard to decipher, but after reading hundreds of them you will get better at it. If your program has no mistakes Fortran will simply return a DOS prompt - that is good news because it means Fortran has successfully created a compiled file. By default this new file is given the name a.exe. (You can give the compiled file a name of your own choosing by typing g77 area.f -o name.exe to compile the program - but usually there is no reason not to accept the default name.) Your compiled file, also located in the h directory, is now executable - that means the program is ready to run.

Running a Program

If your compiled file has the default name a.exe, you simply type a and return to run it (or name and return if you gave the file another name). After you run the program and see how it works, you can return to your editor and revise it as you wish. It is perhaps better to keep two windows open - both the Fortran window and the editing window - so that you can quickly switch from one to the other with a mouse-click. After revising a program, you must save and compile it again before changes take effect.

If you do enough Fortran programming, sooner or later you will err and create and run a program that never stops. In such a situation, type "Control-C" to interrupt the execution of the program.

Now that we have discussed the basic nuts and bolts of creating and running a Fortran program, we discuss some terminology and commands. You will probably find that most of these remind you of similar things in Basic.

Program

Every Fortran program must begin with a program line, giving the name of the program. Here are examples:

									program quadratic
									program mortgage
									program primes

Variables, Declarations, Types

After the program name come the declaration statements, stating the types of the variables used in the program. A variable name consists of characters chosen from the letters a-z and the digits 0-9; the first character of the name must be a letter. You are not allowed to use your program name as a variable, nor are you allowed to use words reserved for the Fortran language, such as "program", "real", "end", etc.
The variable types in Fortran are
1)  integer (in the range from about - 2 billion to + 2 billion)
2)  real (single precision real variable)
3)  double precision (double precision real variable)
4)  character (string variable)
5)  complex (complex variable)
6)  logical (logical variable)
As illustration, the declaration statements
										real r, area
										integer M, N
										double precision a, b

declare that r and area are single precision real variables, that M and N are integers, and that a and b are double precision real variables.

If you do not declare the type of a variable, Fortran will by default make it an integer if it starts with one of the letters i through n, and will make it a single precision real variable otherwise. However, it is normal (and good) programming practice to declare the type of every variable, as otherwise mistakes are easily made.

The implicit quantifier before a type declaration makes all variables starting with the listed letters of the specified type. For example, the declarations

									implicit integer (i-m)
								    implicit real (r-t)

make variables starting with i, j, k, l, m integers, and those starting with r, s, t real. However, the implicit quantifier is probably best avoided, as programmers with short memories will make mistakes.

A declaration statement is nonexecutable - that is, it provides information but does not instruct Fortran to carry out any action. Declarations must appear before any executable statement (a statement that does tell Fortran to take some action).

Assignment

The equals sign "=" assigns the variable on the left side the value of the number or expression on the right side (exactly as in Basic).

Parameter

The parameter statement works like CONST in Basic - it specifies a value for a constant. The syntax is
parameter (name = constant expression)

where name is replaced by the name of the constant, and constant expression by an expression involving only constants. Thus
parameter (pi = 3.14159)

specifies a value for the constant pi, while the succeeding statement
									parameter (pi = 3.14159)
									parameter (a = 2* pi, b = pi/2)

fixes values of new constants a and b in terms of the old constant pi. Remember that once a constant is defined you are not allowed to change its value later.

All parameter statements must appear before the first executable statement.

Comments

A comment is similar to an REM statement in Basic. You can indicate a comment by placing a "c" in column 1 and then the comment in columns 7-72. Alternatively, you can use an exclamation point "!" to indicate a comment; it may occur anywhere in the line (except columns 2-6). Everything on a line after an exclamation point becomes a comment.

Print *

The command "print *" is analogous to PRINT in Basic; it instructs Fortran to print items to the screen. Examples are

									print *, x
									print *, "The solution is ", x
									print *, 'The radius is', r, 'and the area is', area

Note that a comma follows "print *", and that commas (instead of semicolons as in Basic) appear between successive items to be printed. Observe also that either double or single quotes may enclose strings. The command "print *" on a line by itself (without a comma) serves as a line feed.

Read *

The command "read *" is analogous to INPUT in Basic. Examples are

								read *, radius
								read *, A, B, C

In the first example the program pauses to allow the user to enter the radius. In the second example the user types the values of A, B, and C, separated by returns; alternatively, the user can type A, B, and C separated only by commas, and then one final return.

End

The end statement marks the end of the main Fortran program or of a subprogram. (It cannot be used in the middle of the program, as in Basic.)

Operations of Arithmetic

Here are the common arithmetical operations in Fortran:

Additionx + y
Subtractionx - y
Multiplicationx * y
Divisionx / y
Exponentiationx ** y

Fortran performs exponentiations first, then multiplications and divisions, and lastly additions and subtractions. (When in doubt, use parentheses!)

Be careful with division. If m and n are integers, then m/n is truncated to its integer part. Thus 3/4 is evaluated as 0, and 25/6 as 4. When working with constants rather than variables you can avoid this problem by using periods after integers. For example 3./4. is evaluated in the standard way as .75, as Fortran treats 3. and 4. as real variables rather than as integers.

Intrinsic Functions

Many standard mathematical functions are built into Fortran - these are called intrinsic functions. Below is a table of some of the functions most commonly used in mathematical programming. All trig functions work in radians. (Note that arguments of functions must be enclosed in parentheses.)

									abs(x)
								c	absolute value of x

									acos(x)
								c	arccosine of x

									asin(x)
								c	arcsine of x

									atan(x)
								c	arctangent of x

									cos(x)
								c	cosine of x

									cosh(x)
								c	hyperbolic cosine of x

									dble(x)
								c	converts x to double precision type

									exp(x)
								c	exponential function of x (base e)

									log(x)
								c	natural logarithm of x (base e)

									mod(n,m)
								c	remainder when n is divided by m

									real(x)
								c	converts x to real (single precision) type

									sign(x,y)
								c	changes the sign of x to that of y

									sin(x)
								c	sine of x

									sinh(x)
								c	hyperbolic sine of x

									sqrt(x)
								c	square root of x

									tan(x)
								c	tangent of x

									tanh(x)
								c	hyperbolic tangent of x
								

Math across the UH system


UH System

Quick links

System-wide Math Course Coordination Meeting

Lower Division Math Courses

Calculus Courses

Syllabi for UH Manoa Calculus Courses

Lower Division Math Courses


Equivalencies Across the University of Hawaii System, Chaminade and HPU for Lower Level Mathematics Courses

PDF format

Syllabi for UH Manoa Calculus Courses

215 syllabus

241 syllabus

242 syllabus

243 syllabus

244 syllabus

251A syllabus

252A syllabus

253A syllabus

System-wide Math Course Coordination Meeting

Representatives of the various Math Departments in the UH System met at
Kapiolani CC to discuss the coordination of our programs. There were

  • 7 faculty members from UH Manoa
  • 2 from the UH office of the Vice Chancellor for Academic Affairs,
  • 1 from UH Hilo,
  • 1 from UH West Oahu,
  • 5 from Kapiolani CC,
  • 0 from Honolulu CC,
  • 4 from Leeward CC,
  • 2 from Windward CC,
  • 1 from Kauai CC,
  • 1 from Maui CC,
  • 1 from Hawaii CC,
  • for a total of 25.

This report is an informal summary of the discussion.

I. Calculus

Overall we are in fairly good
shape with respect to calculus. The course syllabi are similar at the
different campuses, and articulate smoothly. We will obtain the course
descriptions/syllabi and make them available for comparison. These should
be sent to J. B. Nation (email address listed at the bottom).

UH Manoa has revised its numbering scheme for calculus (241-242-243-244),
while the other campuses have kept the traditional scheme (205-206-231-232).
The system would like us to eventually adopt a uniform scheme.

The use of computers was discussed. Most campuses use computers in
calculus, and most instructors feel that it is an effective tool for
illustrating calculus concepts. The way in which the computer is used
varies some with the instructor, but this was not thought to be a major
issue. A few campuses still do not have adequate facilities to do this
effectively.

There are two minor differences in the curriculum. Following requests
from the Engineering College, Manoa now has vectors in Calculus I and
an introduction to differential equations in Calculus II. Both of these
seem to fit rather well, and we would like to suggest that other schools
consider it.

The importance of completing the syllabus in all calculus courses
was noted.

Standards in calculus has not been a major problem, with the exception
of the usual anecdotal reports. (None of us wants to be held responsible
for our worst C student.) It is important that we keep it this way.

The applied calculus course, Math 215 at Manoa, was discussed as a
viable alternative for calculus I. Currently, roughly 40% of the first
semester calculus students at Manoa are in 215. While the course is
slightly more applied and less theoretical than 205/241, it is intended
to be a substantial calculus course. While having two (or more) options
might be difficult for the smaller schools, other campuses have a large
enough calculus enrollment to justify the option. Smaller campuses could
consider alternating the courses.

Business calculus, Math 203 at UHM, is a less substantial alternative.
It remains true, however, that we can offer a better business calculus
course than business or agriculture departments. If there is enough
demand, offering a “better business calculus” would be a service to
our students.

II. Math 100

There was a major discussion
about the spirit and topics of Math 100. There was general agreement with
the principle that Math 100 should introduce students to the beauty and
precision of mathematics, including mathematical reasoning as well as
counting and algebra. The argument as to which topics best serve that
purpose was more vocal. One side argued that financial math and probability/statistics
did not serve this purpose well. The response was that these topics have
meaning for the students because of their applicability, and that they
illustrate the use of important ideas such as geometric series. It was
emphasized that, the memo of 15 years ago notwithstanding, no one should
dictate the topics for Math 100. Rather, we should insist that a variety
of topics and approaches be covered, and that these be done in a non-cookbook
fashion.

It was noted that teaching Math 100 in a reasonably-sized class can
be much more effective than a large class, but this is a matter over
which we have little control.

With respect to the problem of the Manoa Gen Ed requirements, see
below.

III. Articulation

According to Executive policy
E5.209 the AA degree at any UH community college satisfies the Manoa Gen
Ed requirements, and any 100 level non-technical course transfers to any
other UH institution. The say of the “receiving institution” in this situation
is somewhat cloudy, but it is clear that the administration would prefer
that they say “yes.” However, the various colleges may (and do) have additional
core requirements in addition to the Manoa Gen Ed requirements, and the
transferred credits may not apply to these additional requirements.

Problems with non-Fast Track approval were due to the fact that we
were to approve equivalencies only, and did not have the authority to
approve courses per se.

The Manoa Symbolic Reasoning requirement (FS) is not a math requirement.
It was not written by or for math people, nor specifically approved
by them. The broadly written hallmarks are hard to satisfy with the
broad class of our elementary courses. Nonetheless, that is the objective.
In particular, Math 100 is no longer a quantitative reasoning course,
it is a logic course (!).

A more minor problem: Math 103 – “College Algebra” – is designed for
students transfering to HPU, Chaminade and UNLV (etc). Nonetheless,
it transfers to UHM for credit, though the same course at other schools
probably does not.

IV. Elementary Education

History: Manoa’s old Math
111 failed because we didn’t give high enough grades. This left us in
the undesirable position of having no role in the education of primary
teachers, while those students took Math 100, an inappropriate substitute.

Some folks in the College of Education were concerned about this situation,
and joined us in attempting to revive a math course for elementary education
majors. UHM has added Math 111 and 112, and the Big Island schools have
107-108.

Supposedly at least the first course will be required starting in
2006 (!). It is good for the state and education for us to be involved
in this, if it flies.

The problem solving (constructivist approach) is crucial, but too
limiting to be used exclusively. More experience should help find a
balance. Standards can be a problem, but again experience will help
us adjust this.


MATH 100 satisfies the general education requirement for quantitative reasoning.

For details, see Topics
in Mathematics (Math 100)

MATH 100 should include:

Proofs. The student should be able to follow and present some basic
proofs. The goal is to develop critical thinking skills.

Topics which illustrate the beauty and power of mathematics. Topics
should include at least a few topics from advanced math courses and
their applications such as topology, group theory, network theory, etc.
The goal should be an appreciation of what mathematicians do.

Algorithms should not be used without developing their derivations.
The goal should be to develop the logic behind formulae.

Topics may include the history of number systems to illustrate the
universality of mathematics, as well as the cultural differences. The
goal should be to illustrate the advantage of and encourage the appreciation
of different perspectives.

Topics may involve the mathematics behind popular “logic” puzzles.
The goal is to illustrate what “common sense” is expected by society.

Participants

To foil email harvesters, addresses in the above binary image can
not be cut and pasted.

Calculus Courses

UHM UHH HCC KCC LCC WCC Hawaii Kauai Maui
Computer Lab 241 205 206 206 206 205 thru 232
242 206
ODE’s 242 206 232 232 205 206 232
232 232
Polar 244 231 231 231 231 231 231
Vectors 241 231 231 231 231 231 231
243
Series 242 206 206 206 206 206 206 206 206