ADEWUYI at NASS 04 CSC 232 Scientific Computing Lecture Note
ADEWUYI at NASS 04 CSC 232 Scientific Computing Lecture Note
Scientific Computing (or computational science) is doing whatever it takes to solve scientific and
engineering problems using computers. Algorithms for standard problems in computational science
are presented. The basics of the object-oriented programming language Fortran are taught to facilitate
the student's implementation of algorithms.
1
The universe of scientific computing/computational science
In this course:
• We are mainly interested in the implementation of computational algorithms which can be used
for scientific models
• We will be using the programming language fortran 90 to implement algorithms
You will not be required to understand the science where the problems come from (Although it
makes it more interesting) and you only need a bit of calculus such as knowing about derivatives and
the concept of integration. We will review the math as needed.
• We will learn the basics of fortran 90 in the context of some basic problems in computational
science such as
2
TALKING TO COMPUTERS
• A computer always does exactly as you tell it
• Instructions for computers are in basic machine language that tells the hard ware to do things like
move a number stored in one memory location to another location, or do simple binary
arithmetic.
• Almost no computational scientist really talks to a computer in a language the computer
understands.
• To talk with the computer, we will first open a terminal window. The terminal runs a shell. These
commands get translated to basic machine language which the user does not have to know.
• A shell is a name for a command-line interpreter; i.e., a place where you enter a command for the
computer to obey. Another term for shell might be user interface. You can think of these shells
as the outer layers of the computer's operating system. Multiple copies of the same shell can be
running on the same machine with one or several users.
• CSH or bash are commonly used shells
• The operating system is a group of instructions used by the computer to communicate with users
and devices, to store and read data, and to execute programs.
• The operating system is itself a group of programs that tells the computer what to do in an
elementary way. It views you, other devices, and programs as input data for it to process. The
operating system is like an office manager.
• The reason for this complicated system is to make life easier for the user by letting the computer
and its operating system take care of the tedious work and let you communicate with the computer
in a language closer to your everyday language.
• Common examples of operating systems are Unix, OSX, Windows.
COMPUTER LANGUAGES
• The basic classes of languages are high-level interpreted languages and high-level compiled
languages.
• Examples of high-level interpreted languages are symbolic algebras such as Mathematica, Maple,
Python and the early programming language Basic.
• Examples of high-level compiled languages are C/C++, Fortran, Java (actually Java is considered
semi-compiled)
• When you submit a program to a computer in a compiled language, the computer uses a compiler
to process it. The compiler is another program that treats your program like a foreign language
and uses a built-in dictionary and set of rules to translate it into basic machine language.
• If you make a mistake in your program which violates one of the rules or has a command which
is not in its built-in dictionary, then the compiler will issue error messages and the program will
fail to compile.
• Once all the errors are resolved, the compiler turns the Fortran text into instructions appropriate
for that machine.
• The translated statements ultimately form an executable code that runs when loaded into the
computer's memory. The resulting executable code can be run on ANY machine of that type.
3
STEPS IN RUNNING A CODE
1. Use an editor such as gedit to create a fortran file with the extension .f90
2. Open a terminal window and compile the code using gfortran. You must be in the same directory
as your code (or indicate where the file is)
3. Debug the code, i.e., remove all compile-time errors; this makes take several tries
4. Once the code compiles, execute the code.
1957 Fortran I
1966 Fortran IV
1972 C
1978 Fortran 77
1986 C++
1991 Fortran 90 ANSI C, GNU C
1996 C++ Release 3 Java
2006 Fortran 2003 Java 1.5
FORTRAN 90
• Why aren't we using Fortran 2003? - no compilers available
• Fortran is probably the easiest of the three languages (Fortran, C/C++, Java) to learn
• Properties
➢ not case sensitive
➢ increasingly object-oriented
➢ very efficient
➢ easy array operations
➢ multi-dimensional arrays allowed
➢ modules
➢ polymorphism, function overloading, etc.
➢ lacks some capabilities of C++
• all fortran 90 files should have the extension .f90
• if your file has the extension .f then the compiler assumes it is a fortran 77 file
A SIMPLE PROGRAM
Now we want to look at a program whose purpose is to “say hello", i.e., it just prints out the statement
Hello World
program hello_world
! program to say hello
print *, "Hello World"
end program hello_world
• The program begins and ends with a program statement.
• Comment statements begin with an ! and are ignored by the compiler.
• A simple print statement is used to write out the desired statement.
• Remember that fortran is NOT case sensitive so we could have typed, e.g.
PRINT *, "Hello World!"
or
PrinT *, "Hello World!"
instead of
print *, "Hello World!"
program sum_integers
!
! This program sums the integers from 0 to n and prints the result
! The user is asked to input the number of integers to sum.
!
! *****************************************************
! *****************************************************
!
implicit none
!
integer :: n
integer :: i
integer :: value
!
! *****************************************************
!
! Ask user to read in the number of integers you want to sum
!
print *, " Enter the number of integers you want to sum "
read *, n
!
value = 0 ! initialize the sum to zero
!
! Repeatedly add the integers up to n
do i = 1, n
value = value + i
end do
print *, " The sum of the first ", n, " integers is ", value
! *****************************************************
6
FORTRAN BASICS
• Fortran 90 is a free format language which means that you can start or end a statement in any
column
• Fortran 77 is not free format
• Fortran is not case sensitive
Program is the same as program is the same as PROGRAM
Comments statements should be added throughout program for readability and clarity.
• Many editors use text coloring to make your code more readable and to _nd
• errors more easily.
• The program and end program , declaration is usually one color
• Comments are usually printed in another color.
• We will also see that do loops, conditionals are highlighted in a specific color.
• Read and write statements are highlighted.
PROGRAM STATEMENTS
• First statement of each computer program is a program statement
• Syntax
➢ the word program followed by at least one space followed by the name of the program
➢ for example, the program which uses Monte Carlo for determining _ might be called
program mc pi
➢ the name of the program does not have to be the same as what you call the program but
typically you would call this program mc pi.f90
• Syntax
➢ the words end program followed by the name of the program
➢ the program name must be the same as in the initial program statement
➢ for our example, the end program statement is
end program mc pi
7
• For example, if your code consists of the following you will get an error message
upon compilation. Why?
program test1
implicit none
print *, "test"
end program test
Comment Statements
• Comment statements are essential for documentation.
• You will write many codes during this course and by the end of the semester (let alone next
year) you will have forgotten what a code does or how you are implementing an algorithm.
• Comment statements will help you (and others) figure out what your code does.
• Fortran ignores comment statements - they are for human use only
• Fortran must know which statements are to be executed and which statements are just there
for your information.
• How does fortran know when a statement is a comment statement?
➢ An exclamation mark ! tells fortran to ignore what comes after it
➢ The exclamation mark is often at the beginning of a line if you are adding a sentence
describing what the code does
➢ Other times you may want to add a comment at the end of a line
Declaration Statements
• When we write a code, we use variables.
➢ For example, the integer n may be the total number of integers we are summing.
➢ Or average may be our average of n numbers which is a real number
• Each variable must be assigned a memory location to be stored in.
• In order for the compiler to do this, it must know what type of variable it is.
• For example, an integer requires less storage than a real number.
• Consequently, we must declare each variable that we use.
• In Fortran 77 programmers used to declare that any variable starting with I through n were
automatically integers. This is now considered bad programming practice.
8
Implicit None Statement
• We will always use the declaration
implicit none
• This statement appears before statements declaring our variables as real, integer, etc.
• Its purpose is to tell the compiler that we will declare every one of the variables we use.
• This is very useful in debugging a code.
• For example, if we have a variable named psi which we have declared as a real number and, in
a statement, we accidentally type phi then the compiler will give us an error that says undefined
variable.
• If you do not use this statement then the compiler will assume that any variable beginning
with i, j, k, l, m, n you do not declare is automatically an integer; variables beginning with the
remaining letters are automatically reals.
Data Types
There are 5 basic data types
_ integer
_ real
_ complex (we will not be using complex arithmetic)
_ character
_ logical
Every variable name you use must be declared to be one of these five types because the compiler
needs to associate this variable with a memory location.
For example
integer :: n
Integers
• An integer is a whole number
• It can be positive, negative or zero
• Examples
0 5 -45 1024 -234567
9
Real Numbers
• We will use the terminology real number or floating-point number interchangeably.
• Real numbers will always contain a decimal point but no commas.
• Real numbers may be entered using standard decimal expression or in exponential notation.
• Examples
0:0 0:5231 - 45:1 1024:79
0.0E0 5.231E-1 - 4.51E1 1.02479E3
• Syntax for declaring a variable average a real number
real :: average
Characters
• A character (sometimes called a string) is a sequence of symbols from the fortran character
set.
• For us, characters will usually include letters, numbers, periods, underscores, and blanks. Note
that your author left off the underscore character “_"
• Examples
approx pi:txt ( 13 characters) jane doe ( 8 characters including blank)
• Note that the syntax (len=20) allocates a maximum of 20 characters for the string filename
10
REVIEW QUESTIONS.
1. A _______________ is a data structure in which additions are made at one end and deletions are
made at the other end. queue
2. In a FORTRAN program, assuming x = 2.0, a = 2.0, and b = 4.0, what is the value of y if y = a
* x + b ** 2 / x? 14.0
3. itemize the five (5) basic data types in FORTRAN language? Integer, Real, Complex, Logical,
4. Give the Exponential notations for 1024.79? 1.02479E3
5. A graph is a pictorial representation of a set of points or nodes termed as _______________,
and the links that connect the vertices are called _______________. Vertices and edges.
6. The _______________ is a function describing the amount of memory an algorithm takes in
terms of the amount of input to the algorithm. Space complexity
7. What is a flowchart? A pictorial representation of an algorithm
8. If x = 50.7, y = 25.3, and z is defined as integer z, calculate z = x + y. 75
9. An _______________ is a single purpose system where the function is built at hardware level
whereas with a general-purpose system a lot of function can be programmed without modifying
its hardware. Embedded System
10. A _______________ is a data structure in which additions and deletions are made at the top of
the stack. stack
11. Express –1.56 x 1012 in its Exponential notation. -1.56E12
12. The complexity of an algorithm is studied with respect to the following 3 cases:
_______________, _______________ and _______________. Worst, Average & Best Case.
13. Give an appropriate example of Named constants declared with its parameter attribute?
Real, parameter :: pi = 3.1415927
14. The _______________ is a group of instructions used by the computer to communicate with
users and devices, to store and read data, and to execute programs. Operating System
15. _______________ are large computers that can support very many users while delivering great
computing power. Mainframes
16. Fortran was created by a team, led by? John Backus at IBM in 1957
17. _______________ is a systematic way to organize data in order to use it efficiently. Data
Structure
18. All FORTRAN programs start with the keyword _______________ and end with the keyword
_______________, by the name of the program. Program and end program
19. A _______________ is a system program, which takes the object code of a program as input and
prepares it for execution. loader
20. If radius = 5.0, and pi = 3.142, pi is defined as integer pi and areacircle, calculate the areacircle =
pi*radius**2. 75
11
Continuation of a statement
• If a statement extends over more than one line you can continue the statement by putting the
symbol & at the end of the line
• For example, the following two statements are equivalent
b=a+7
b=a&
+7
• When writing a code in an editor you don't want to make the statements too long
• This should be used sparingly because it reduces the readability of your code which makes
debugging harder.
• If we want to print two variables, say approximation and error then we put them in a list and
separate them by a comma
print *, approximation, error
• We can combine these two into one statement; for example, to print out the final error (call it
error) after the method has converged to an acceptable answer we type
print *, " the method has converged; the error is ", error
• These are all called unformatted writes. We can also specify the format we want to use to write
out a variable; e.g., how many decimal places to include, etc. We will return to the print
statement later.
• Again, the syntax read * means to read from the screen just like print * writes to the screen.
• When the program is executed, execution is halted until this value is read in.
It will NOT prompt you to do this.
• Consequently, if you are reading from the screen, you should always put a write statement
before this to tell the user that he/she will be asked to input a value.
For example, if the user needs to input the number of integers from the screen, then you should
include the lines
print *, " enter the number of integers you want to sum"
read *, n
13
Numeric Operations
• In Fortran the numeric operations use standard symbols except exponentiation.
addition +
subtraction -
multiplication *
division /
exponentiation ** (not ^ ) (irritating, I know)
Mixed Arithmetic
• Most of the time, we will be performing numeric operations on variables. For example, we
may want to compute a/b where a; b has been defined.
• Care must be taken to distinguish between dividing two integers and dividing two real
numbers.
5=4 is not the same as 5.0=4.0
For example,
integer :: n,m
real :: value
n=5; m=4
value = n/m
computes value = 1 whereas
real :: n,m
real :: value
n=5.0; m=4.0
value =n/m
computes value = 1.25
• Moreover, we will see that if we use mixed-arithmetic (i.e., trying to combine integers and
reals) we can sometimes get in trouble.
• Using mixed arithmetic is considered bad programming practice. In this class you will lose
points on your program if you use it!
• For example, instead of writing 2.0 +3 / 7 you should use 2.0 + 3.0/7.0
Order of Operations
• Fortran has a set of rules for the order in which operations are computed. The order is the
way we normally expect in mathematical expressions.
• The priority rules for parentheses-free expressions are:
1. perform all exponentiation; if more than one go right to left
2. multiplications and divisions are performed next - left to right
14
3. additions and subtractions are performed last - left to right
• We can modify the standard priority rules by including parentheses.
• The order of priority for parentheses is inner to outer.
• The rule of thumb you should follow, is when in doubt, use parentheses.
• Parentheses can also make complicated expressions easier to read.
Examples
• The expression
x+y*z
In this case the parentheses take precedence and x is first added to y and the result multiplied
by z .
• In the expression
x + y **2 * z
exponentiation takes precedence so it is done first; then the multiplication and finally the
addition. Thus the expression means to first square y , then multiply the result times z and add
the result to x .
• Note that the following expressions are not the same
2.0 ** 3 **2 = 29 = 512 (2.0 **3) **2 = 82 = 64
We first perform the division 5.5/2.35 (inner most parentheses), then the expression inside
the outer parentheses is done using priority rules - raise the result to the fourth power and
then divide by two. Finally, we multiply result by 4.1
• Warning - a programming error that we often get is mismatched parenthesis.
This means that we have inadvertently missed a left or right parenthesis.
For debugging ease, I like to put a space between the parenthesis and the quantities to be
computed so that they are more obvious.
• In the classwork you will see this compilation error when you debug a code.
Intrinsic Functions
• A fortran compiler has many built-in or intrinsic functions for standard mathematical
operations.
• As an example, consider the quantity
4e.5 + sin 90o - ln 2.79
4.0 * exp(0.5) + sin(pi/2.0) - log(2.79)
Variables
• Most of the time we will perform a calculation and assign the value to some variable (which
has been declared in a type statement). Alternately, we may want to define a variable as a
parameter (_xed forever in the program) such as pi.
• Of course, fortran has rules for naming variables.
➢ must begin with a letter
➢ other characters may be letters, numbers or underscores
➢ must be _ 30 characters
• You can not name a variable a name that already means something in fortran.
For example, you can't name a variable sin since it is an intrinsic function.
• We have a rule for naming variables - The name must be meaningful!
• As an example, consider the following two lines of code for calculating the
area of a circle. Which one do you think is easier to follow?
a = 5.0
b = pi * a **2
or
radius = 5.0
area circle = pi * radius**2
16
• Do loops allow us to easily repeat a section of code.
• Here we will only investigate counter-controlled do loops
• Syntax for the do construct (counter-controlled)
• The counter control, initial value, final value and increment must be integers
• The increment is optional; if omitted it is assumed that the increment is 1
• Negative increments are allowed.
• The initial or final values can be zero
• How does it work? Consider the statements
do i = 2, 10
…..
end do
1. The counter control i is set to the initial value, here to 2
2. i is then checked against the final value (here 10) to see if it is _ the final value (assuming final value
is positive)
➢ If less than or equal to the final value, proceed to step 3
➢ If greater than the final value, terminate loop (go to next statement after end do )
3. all statements between the do and the end do statements are executed
4. the increment is added to i (here the increment is 1 so that i = i +1)
5. Return to step (2)
Example
integer :: sum integers
integer :: i
sum integers = 0
do i = 1, 5
sum integers = sum integers + i
end do
• i = 1 - sum integers = 0 + 1 = 1
• i = 2 - sum integers = 1 + 2 = 3
• i = 3 - sum integers = 3 + 3 = 6
• i = 4 - sum integers = 6 + 4 = 10
• i = 5 - sum integers = 10 + 5 = 15
• the loop is terminated when i = 6 since this value is greater than the final value
• Note that for readability we have indented the commands inside the do loop
17
A Simple Conditional
• Often, we need to test to see if a particular condition has been met. For example, if our error
is less than some tolerance.
• Fortran provides several conditional statements for this purpose.
• First, we look at the simple if statement where we test a condition and have only one
alternative.
Syntax for the case when we only want to perform one statement if the condition is satisfied
if ( condition ) statement
Examples
if ( a < 2 ) b = a ** 4 ; if ( error < tolerance ) stop
Syntax for the case when we want to perform several statements if the condition is satisfied
if ( condition ) then
statements
end if
if ( error < tolerance ) then
print *, " method has converged"
stop
end if
An IF ELSE Construct
Often when we test we want to do one thing if the condition is satisfied and another if it is not; i.e.,
we have 2 alternatives. In this case we can simply add an else to our if then construction
if ( condition ) then
statements
else
statements
end if
For example, if we want to take the square root of a if a _ 0 but if a is negative you want to print out
an error message, we would have the following IF ELSE
construct
if ( a >= 0.0 ) then
a = sqrt(a)
else
print *, "error: a is less than zero"
end if
18
Symbols for Logical Expressions
less than < .lt.
less than or equal to <= .le.
great than > .gt.
greater than or equal to >= .le.
equal to == .eq.
not equal to /= .ne.
• You can use either the symbol or the text syntax. For example if you want less than you can
use either < or .lt.
• If we wanted to test if a is less than 4
if ( a < 4.0 ) then
• If we wanted to test if a is greater than 2
if ( a > 2.0 ) then
• What if we want to combine these two expressions to check that 2 < a < 4?
Compound Expressions
and .and.
or .or.
not .not.
Exercise
1. Write a program which will read in two real numbers representing the
length and breadth of a rectangle, and will print out the area calculated as
length times breadth. (Use a derived type to represent the rectangle and its
area.)
2. Write a program which will read in five integers and will output the sum
and average of the numbers.
19