Computational PhysicsCourse Pages 1
Computational PhysicsCourse Pages 1
Computational Physics
Solomon Negash
1
Introduction to Computational Physics – Solomon N.
1. Introduction to FORTRAN 90
Introduction
FORTRAN is a general purpose programming language, mainly intended for
mathematical computations in science applications (eg. physics and engineering).
In 1957 the the first FORTRAN compiler was released for the IBM 704.
2
Introduction to Computational Physics – Solomon N.
FORTRAN 66 (ISO Standard 1972)
The hardware is the physical medium, e.g. CPU, memory, keyboard, display etc.
3
Introduction to Computational Physics – Solomon N.
A piece of software is a set of computer program, e.g. operating system,
compilers, editors, Fortran 90 programs.
4
Introduction to Computational Physics – Solomon N.
Variables and Statements
A FORTRAN program consists of a series of statements – which is made up of
alphanumeric, underscore (_) and special characters (see Table 1, p. 6)
Example: x = (-y + root_of_discriminant)/2.0*a)
The alphanumeric characters are the 26 letters, the 10 digits
Statements may contain from 0 to 132 characters per line (a statement may be
blank)
Two basic types of statements are
– Executable: describes the action a program takes when it executes.
– Non-executable: provides an information necessary for a proper operation
of the program.
All statements, except the assignment statement (e.g. BALANCE = 1000), start
with a keyword – END, PRINT, PROGRAM, and REAL.
Generally, there will be one statement per line.
However, multiple statements may appear on a line if they are separated by
semi-colons. eg. A = 2; B = 2; C = 1 5
Introduction to Computational Physics – Solomon N.
Variables and Statements
6
Introduction to Computational Physics – Solomon N.
Variables and Statements
CONSTANT PARAMETER
Derived data type
The ability to define data type of interest to the programmer
Example: matrices, geometrical shapes, lists, interval numbers
10
Introduction to Computational Physics – Solomon N.
Integer, real, complex
Integer: positive, negative and zero
INTEGER (k2) :: i, j
The KIND specifies that INTEGER variables i and j can hold 2-digit integers.
13
Introduction to Computational Physics – Solomon N.
Arithmetic expressions
Arithmetic operator symbol
Operator symbol Arithmetic operation
+ Addition
- Subtraction or unary minus
* Multiplication
/ Division
** Exponentiation
15
Introduction to Computational Physics – Solomon N.
Good programming guidelines
Use comments to clarify the purpose of both sections of the
program and the whole program
Constant
.TRUE.
.FALSE.
Declaration of logical constant
17
Introduction to Computational Physics – Solomon N.
Character
Constant character
type triangle
type (point) :: a,b,c t has components: t%a, t%b, t%c all of type
point, and
End type triangle t%a has components: t%a%x, t%a%y, t%a%z
type (triangle) :: t of type real 22
Introduction to Computational Physics – Solomon N.
Array
Consists of a rectangular set of elements, all of the same type and type
parameters – used to refer a set of group item by a single name
Fixed and dynamical
Real,dimension(-10:5):: vector
We always need to specify the upper bound, the lower bound is optional, and
by default has the value 1.
Fortran allows up to seven dimensions to be specified. 23
Introduction to Computational Physics – Solomon N.
Array
Ex 1. real, dimension(5,4) :: b ››› declares an array with two dimensions,
2. real, dimension(-10:5, -20:-l, 0:1, -1:0, 2, 2, 2)::grid ››› declares seven
dimensions
The size of this second array is:
Arrays of many dimensions can thus place large demands on the memory of
a computer.
The number of dimensions of an array is called rank. Thus grid has a rank of
seven.
A derived type may contain an array component.
Type name
Real, dimension (size) :: vara
End type name
24
Introduction to Computational Physics – Solomon N.
Array
Some statements treat the elements of an array one-by-one in a special
order which we call the array element order.
It is obtained by counting most rapidly in the early dimensions.
The elements of grid in array element order are
grid(-10, -20, 0, -1, 1, 1, 1)
...
grid( -9, -20, 0, -1, 1, 1, 1) The ordering of elements in the array b(5,4).
grid( 5, -1, 1, 0, 2, 2, 2).
This is illustrated for an array of
two dimensions (see fig.)
We reference the element of an
array by specifying its subscript
values.
25
Introduction to Computational Physics – Solomon N.
Array
In general, a subscript may be formed of a scalar integer expression
Example: a(1)
a(i*j) ! i and j are of type integer
a(nint(x+3.)) ! x is of type real
PROGRAM program_name
Implicit none
[declaration statements]
open(unit =”number”, Form=”formatted”, file = “file_name”, status=”new”, &
iostat =”ios”)
31
Introduction to Computational Physics – Solomon N.
Control structure
BLOCK IF statements
if (a .lt. b) then
a) IF (logical expression) statement
sum = sum + a
if (sum > 0.) print*, sum
b) IF (logical expression) THEN end if
STATEMENT
ENDIF
ENDIF
32
Introduction to Computational Physics – Solomon N.
CASE statement
The CASE statement provides a very clear and expressive selection mechanism
b/n two or more courses of action.
It could be programmed entirely with IF statement, but with controllable loss of
clarity.
A general form of CASE is
SELECT CASE (expr) select case (ch) ! ch of type character
CASE (selector1) case (‘c’, ‘d’, ‘r’:)
ch_type = .true.
block1 case (‘i’:’n’)
CASE (selector2) int_type = .true.
block2 case default
real_type = .true.
[CASE DEFAULT end select
blockD]
END SELECT
where (expr) must be integer, character or logical
33
Introduction to Computational Physics – Solomon N.
DO statements
DO variable = start, end, increment
Block of statements
END DO
Example
Program iteration_do
Integer:: i, sum, n
...
! assignment of n
sum = 0
do i = 1, n, 2
sum = sum + i
end do
...
end program iteration_do
34
Introduction to Computational Physics – Solomon N.
DO statements
DO WHILE (logical expression)
Block of statements
END DO
Example:
Program iteration_exit
Real :: value
Real :: x, xlast
real, parameter :: tolerance = 1.0e-6
Value = 50.
x = 1.0 ! initial value (diff. 0)
do
xlast = x
x = 0.5 * (xlast + value/xlast)
if (abs(x – xlast)/x < tolerance) exit
end do
end program iteration_exit 36
Introduction to Computational Physics – Solomon N.
FUNCTION
Advanced programs can be structured by means of procedures or subprograms
FORTRAN 90 enables us to implement subprograms as functions and
subroutines
Subprograms may be internal or external.
We use function:
– To break a problem down into parts, giving us the opportunity to structure
our problem solution
– To avoid the replication of the same or very similar sections of the code
– To build up a library of functions or modules for solving particular sub-
problems
Intrinsic or user defined
It take parameter or argument
Parameters can be an expression
It will normally return a value
It can sometimes take arguments of variety of types
37
Introduction to Computational Physics – Solomon N.
Function
Structure of a function in a program
PROGRAM program_name
IMPLICIT NONE
Real/Integer :: function_name
Real/Integer :: vara1
,
Vara1 = function_name
,
END PROGRAM program_name
– Usually created when a procedure is called and their value lost when
execution returns to the calling program unit
Fortran allows the computer system being used to ‘forget’ a new value, the
unless it has the save attribute.
SAVE attribute
– for the local variable to retain its values between calls to a subprogram the
SAVE attribute can be used on a type statement
Example:
INTEGER, SAVE :: I
Functions and subroutines are very similar except a function returns a single
value, whereas a subroutine returns several results through its arguments.
41
Introduction to Computational Physics – Solomon N.
MODULES
Use of module
– Help programmers to split their codes into small modules
– Consistent definition of precision throughout a program and subprograms
– Use global data, Sharing arrays of data
– For derived data types
The form of a module is
Program main
MODULE module_name USE module_name
… Implicit none
Real :: vara1, vara2
END MODULE module_name
To access module …
The USE statement must be the first statement after the PROGRAM or
SUBROUTINE or FUNCTION statement.
42
Introduction to Computational Physics – Solomon N.
MODULES
module constants
Example: implicit none
real, parameter :: pi = 3.1415926536
real, parameter :: e = 2.7182818285
contains
subroutine show_consts()
print*, "Pi = ", pi
print*, "e = ", e
end subroutine show_consts
end module constants
program module_example
use constants
implicit none
real :: x, ePowerx, area, radius
X = 2.0; radius = 7.0
ePowerx = e ** x
area = pi * radius**2
call show_consts()
print*, "e raised to the power of 2 = ", ePowerx
print*, "Area of a circle with radius 7= ", area
end program module_example 43
Introduction to Computational Physics – Solomon N.
2. Errors and Uncertainties in Computations
– Humans
– Computers
●
Arise from limited precision with
computers to store numbers or
●
B/c algorithms or models can fail
Types of Errors
On June 4, 1996, an Ariane 5 rocket launched by the European Space
Four general types of errors exist to Agency exploded just forty seconds after its lift-off from Kourou, French
Guiana. The rocket was on its first voyage, after a decade of development
plague your computations: costing $7 billion. The problem was a software error (overflow) in the
inertial reference system. Specifically a 64 bit floating point number
relating to the horizontal velocity of the rocket with respect to the platform
was converted to a 16 bit signed integer. Because the floating point value
I) Blunders or bad theory: was too large to be represented by a 16-bit signed integer.
(algorithm)
47
Introduction to Computational Physics – Solomon N.
Subtractive Cancellation
A calculation using numbers that are stored only approximately on the
computer can be expected to yield only an approximate answer.
Applying this to
= 0 or /= 0
48
Introduction to Computational Physics – Solomon N.
Of special importance here the error in the answer increases when we
subtract two nearly equal numbers
B/c we are subtracting off the most significant parts of both numbers
B/c we cannot assume any sign for the errors, we must assume the worst (the
“max” in the above Eq.)
Example: solution of
49
Introduction to Computational Physics – Solomon N.
Round-off Error in a Single Step
Let’s start by seeing how error arises from a single division of the computer
representations of two numbers:
(Ignoring very
small)
We can generalize this error estimation in the evaluation a function
For
50
Introduction to Computational Physics – Solomon N.
Round-off Error Accumulation After Many Steps
There is a useful model for approximating how round-off error accumulates in a
calculation involving a large number of steps.
1. Does it converge?
On first thought we may think, all algorithms converge if enough terms are used,
and if you want more precision, then use more terms.
Good algorithms–are fast & round-off error does not have much time to grow.
Here α and β are empirical constants – may change for different algorithms, may
be approximately constant as
53
Introduction to Computational Physics – Solomon N.
The total error in a computation would be the sum of the two
For small N the first term is larger but ultimately to be overcome by the slowly
growing round-off error.
Example: Fig. a log-log plot of the relative error in numerical integration using
the Simpson rule
The smallest total error will be obtained if we can stop the calculation at the
minimum near 54
Introduction to Computational Physics – Solomon N.
Minimizing the Error
In order to see more clearly how different kinds of errors enter into a
computation, let us examine a case and are known
55
Introduction to Computational Physics – Solomon N.
Most of the error is due to round-off, the double precision results are better.
We can decrease the total error by decrease round-off error using a smaller
number of steps N.
Let us assume another algorithm that converges more rapidly with N
The error is now smaller by a factor of 4 with only 1/16 as many steps needed
In this case the better algorithm is quicker and, by using fewer steps, it produces
less round-off error
Bisection Method
If a root exists in the region for , we can use the bisection
method – simple method to code
y
B/c there is a root in the region, f (x )
We divide the region into two equal parts
x
and
and
58
Introduction to Computational Physics – Solomon N.
Newton-Raphson’s Method
This method is based on linear approximation of a smooth function around its
root.
Here x can be viewed as a trial value for the root at the ith step
, with
59
Introduction to Computational Physics – Solomon N.
Here we have used the notation
The idea of using one value to generate a better value is called iteration
60
Introduction to Computational Physics – Solomon N.
So we might guess that: , somewhere around
We then calculate the zero to be at:
Much closer to the correct answer of 0.739085133 than the initial guess
secant method, or
discrete Newton method
The disadvantage of the method is that we need two points in order to start the
search process. 62
Introduction to Computational Physics – Solomon N.
We are drawing a straight line from the point to
The secant method is more efficient than the bisection method but less
– Forward difference
– Central difference
– Extrapolated difference
64
Introduction to Computational Physics – Solomon N.
Forward Difference
The most direct method for numerical differentiation of a function starts by
expanding it in a Taylor series.
This series advances the function one small step forward:
An approximation for the error follows from substituting the Taylor series:
Yet precision will be lost through the subtractive cancellation on the left-hand
side (LHS) of (1) for too small an h.
66
Introduction to Computational Physics – Solomon N.
Central Difference
An improved approximation to the derivative starts with the basic definition
(2)
Central difference
67
Introduction to Computational Physics – Solomon N.
The central-difference algorithm accurate to order ( before division by
h), while the forward difference is accurate only to order h.
68
Introduction to Computational Physics – Solomon N.
Extrapolated Difference
We can reduce the theoretical error further by combining algorithms whose
sums extrapolate to zero
One algorithm is the central difference using a half step back and a half step
forward
The second algorithm is another central-difference approximation using
quarter-steps:
The combination of the two eliminates both the quadratic and the linear error
terms:
For half step:
**
(3)
Extrapolated difference 70
Introduction to Computational Physics – Solomon N.