Lecture Week1
Lecture Week1
Course Description: This course introduces the student to the science of compu-
tations. 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.
If you make a “C-” or better in this course you can use it to satisfy the FSU
Computer Competency Requirement.
• Homework/Classwork - 50%
• Projects - 15%
• Midterm Exam - 15%
• Final Capstone (Individual) Project - 20%
Expectations: Before each class you should go through the notes for the up-
coming class so that you can get more out of each lecture. After each class
you should review the notes to solidify the concepts introduced, complete any
classwork which you were unable to finish during the lecture period and work on
assigned homework. Please take advantage of office hours. If you have a short
question, then emailing is fine. Be warned that sometimes debugging a computer
code can take longer than you think, so start homework early!
Instructor: Janet Peterson, 444 DSL, jpeterson@.fsu.edu
Invention and
development of
new computational
algorithms
User-friendly
presentation of
solutions
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
• 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.
• Once all the errors are resolved, the compiler turns the Fortran text into
instructions appropriate for that machine.
• The translated statements ultimately form an executeable code that runs when
loaded into the computer’s memory.The resulting executable code can be run
on ANY machine of that type.
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 make take several
tries
4. Once the code compiles, execute the code
Compiled Language History
1957 Fortran I
1966 Fortran IV
1972 C
1978 Fortran 77
1986 C++
• Class accounts exist for everyone enrolled and you log in using your FSU ID
and password.
• Computers you have access to with your class account that have Fortran 90
compilers
– Classroom computers
∗ can be used when you are sitting in front of the machine
∗ can be accessed remotely by the ssh command (more on this later)
– Other computers
∗ computers next to elevator on 4th floor Dirac
• If you want to use your personal computer, then there are downloadable For-
tran 90 compilers (both Macs and PC’s)
– If you want information about this, please see TA
– If you are having trouble downloading this, see TA
Setting up your work space
• Organize your programs into folders or directories. For example, we will pro-
gram several methods for solving a nonlinear equation so you may have a
directory entitled nonlinear methods.
• On the classroom machines you will use UNIX commands to make directories,
move files, duplicate files, etc.
• If you use your personal computer, you may need to transfer files between
your FSU file storage system and that of your personal computer. The sftp
command is used for this. More on this later.
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
or
PrinT *, "Hello World!"
instead of
print *, "Hello World!"
1. Log in using your class account; you should have been sent the information
via email.
2. Go to the class website and look for the file hello world.f90. To download it
RIGHT CLICK the link and use the save command that appears in the menu.
You need to specify where you want the file saved; the best place is your
account (not desktop)
3. Open a terminal window; to do this go to the lower left hand corner and click
the icon next to the browser icon and look under accessories.
4. To compile the program - type gfortran hello world.f90
5. The executable will be automatically called a.out
6. Execute the file by typing ./a.out
7. The output should appear on your screen.
What happens if we make an error in writing our program?
program hello_world
! program to say hello
which tells us which statement it doesn’t understand. If we left off the end
program statement then we get the error
• When you write a program you will need to create it with an editor just like
when you create a text document.
• Certain editors are especially useful for creating a program because they auto-
matically color code the statements which improves readability and debugging
(finding errors)
• I would suggest starting with gedit and then later you can switch to a more
sophisticated editor if you so desire.
• Help is available online by googling “gedit”.
• To modify the existing program click the “red hat” icon and scroll down to
accessories then click the item gedit text editor and click to use edit.
• Under file click open and it should give a list of your files which includes
hello world.f90 Click on it and the file should open.
• Notice the color coding in the file.
• To add statements or modify current statements simply move the cursor
around.
• To copy a line just highlight it and use copy/paste commands under the edit
menu
• Save your new version of the file
Classwork/Homework
Goals today: learn some basic fortran statements and write a code to perform
basic scientific calculator operators
A More Complicated Program
This program sums the first n integers. The program queries the user to tell it
the value of n and then it uses an iteration loop (called a do loop to sum these
integers.
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
!*****************************************************
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
• Many editors use text coloring to make your code more readable and to find
errors more easily.
• The program and end program , declaration are 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
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
• end program statement is last statement of your program
• 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
• 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
• This statement appears before statements declaring our variables as real, in-
teger, 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
• 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
declares the variable n as an integer.
Integers
• We will use the terminology real number or floating point number interchange-
ably.
• Real numbers will always contain a decimal point but no commas.
• Note that the syntax (len=20) allocates a maximum of 20 characters for the
string filename
Logicals
• So when you declare a variable as a logical, you are saying that it can only
have the value true or false
• Syntax for declaring a variable flag converge as a logical
logical :: flag converge
• Fortran allows us to do this when we declare the variable through the parameter
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
More than one expression on a line
• Almost all the time, we will have a single expression on a single line of the
file.
• Sometimes, however we may have several assignments that we want to put
on the same line of the file for compactness.
• This can be done by separating the expressions by a semicolon
x1 = 1.0; x2 = 1.0; x3 = 1.0
• This should be used sparingly because it reduces the readability of your code
which makes debugging harder.
The Assignment Statement
• The assignment statement just assigns a value to a variable; the variable may
be integer, real, etc.
• For example, if radius is declared real and n is declared an integer then we
could have
radius = 5.0
n = 5
• If n is declared an integer and we write
n = 5.1
then most compilers won’t give you an error, it will simply truncate n to 5.
• If radius is declared real and you type
radius = 5
then the compiler will set it to 5.0 but you should always distinguish between
reals (with decimals) and integers (without decimals) for good programming
practices.
Printing our Results to the Screen
• If we don’t have too much output, then we can simply print to the screen.
• We can either print text or the value of some variable
• To print text to the screen we must enclose the text in either single or double
quotes
print *, " the method has converged "
• Note that print * means to print to the screen
• We can print the stored value of a variable to the screen by
print *, variable name
• 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.
Reading Input from the Screen
• We looked at a code which summed the first n integers. The program queried
the user to enter the value of n. You simply type it when asked and hit return.
• To do this, we can use the read command and tell the compiler we want to
read the data from the terminal window.
read *, n
• 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
Writing a fortran program to use as a basic scientific calculator
• One of the simplest (but not too useful) programs to write is to perform
calculations like a scientific calculator
• For example, we could compute the value of
π 0.234
√
sin + e + (2.345 − 4.5)5
9
• Fortran has some built-in functions which are called intrinsic functions for trig
functions, square roots, exponentials, logs, etc. - just like you have keys on
your calculator.
• The first thing we need to know is what are the symbols for numeric operations
- adding, multiplying, exponentiation, etc.
• We also have to be concerned about order of operations. However, just like
on paper, if you use parentheses freely then you can minimize problems. For
example, does this expression mean 72 or 3 + 42 = 5 ?
3+4/2
Numeric Operations
addition +
subtraction -
multiplication *
division /
exponentiation ** (not ˆ ) (irritating, I know)
• For example, if we want to compute
6 908.5
(5.1) −
7.36
we type
5.1 ∗∗6 − 908.5/7.36
Mixed Arithmetic
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
• 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:
• The expression
x+y∗z
means to multiply y times z and add the result to x .
• It is not the same as 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
• Here’s an example of an expression using nested parentheses
4.1 ∗ ( (5.5 / 2.35) ∗∗4 / 2.0 )
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.
Classwork/Homework
You should demonstrate to us that you have a properly compiled and executed
the code by the start of next class. It does not have to be handed in.
Intrinsic Functions
• A fortran compiler has many built-in or intrinsic functions for standard math-
ematical operations.
• I have posted a list of intrinsic functions in fortran under the Miscellaneous
Files heading on the website
• The trig functions are standard - for example
sin(x) cos(x) tan(x) asin(x) sinh(x)
– Here asin is the arcsin (i.e., sin−1) and sinh is the hyperbolic sine.
– Note that each function has an argument enclosed in ( ) which is an
angle in radians.
– Note that cos (pi/ 3) is cos 60◦ not cos (60), assuming of course that
pi has been appropriately defined.
• The natural log, log10, e, and square root function are defined by
log(x) log10(x) exp(x) sqrt(x)
• If we want to compute log2 x then we must convert this to the natural log (or
log10), i.e., log2 x = ln x/ ln 2.
• Note that the natural log is not ln
1
• Note that there is no built-in function for like on your calculator.
x
• As an example, consider the quantity
4e.5 + sin 90◦ − ln 2.79
4.0 ∗ exp(0.5) + sin(pi/2.0) − log(2.79)
where pi has been appropriately defined.
• There are many more intrinsic functions or procedures which we will introduce
as we need them
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 (fixed 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.
• I 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
The Assignment Statement
• We have already seen that the assignment statement just assigns a value to
a variable.
• However there is one assignment statement which may seem confusing at first.
Consider the statements
a = 3.0
• This statement assigns the value 3 to a.
a = a + 5.0
• This statement says take the current value of a (which is 3) and add 5 to it;
a is now 8.
a = a / 4.0
• This says take the current value of a (8) and divide it by 4. a is now 2.
A Simple Do Loop for Repetition
end do
• 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
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
An example of a do loop with a negative increment
real :: ai
integer :: i
a i = 100.0; print *, a i
do i = 4,1,-1
a i = a i / 2.0; print *, a i
end do
• 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
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
• 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.
• To check that the error is less than or equal to the tolerance or the number
of steps (say n) is greater than some maximum number of steps
if ( error <= tolerance .or. n > max steps ) then
Classwork/Homework