summary of previous weeks

48
Summary of previous weeks BIL 102 Introduction to Scientific & Engineering Computing

Upload: lars-kerr

Post on 01-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Summary of previous weeks. BIL 102 Introduction to Scientific & Engineering Computing. Course Contentents. Introduction to computing Basic FORTRAN Selective execuation Repetitive execuation Input/output Programming with functions Arrays, Data types, Files - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Summary of previous weeks

Summary of previous weeks

BIL 102

Introduction to Scientific & Engineering Computing

Page 2: Summary of previous weeks

Course Contentents Introduction to computing Basic FORTRAN Selective execuation Repetitive execuation Input/output Programming with functions Arrays, Data types, Files Pointers and linked structures

Page 3: Summary of previous weeks

Course WEB site

http:://www3.itu.edu.tr/~F90

Textbook

Programming in F T.M.R. Ellis and Ivor R. PhilipsSeveral copies at the M.I.L.’s Reserve Section Photocopies available Fen-Edebiyat printshop

Page 4: Summary of previous weeks

Registration

Page 5: Summary of previous weeks

How do we tell these days a computer what to do?

Compiler

Source program(high level language)

Object program(machine language)

Page 6: Summary of previous weeks

So, why Fortran?

Concise language Good compilers producing efficient

machine code Legacy: high-quality mathematical

libraries (IMSL, NAG, …) available New version have features helpful

for parallelization

Page 7: Summary of previous weeks

The F language

F & Fortran 90

FFortran 77

Fortran 90

Easy to learn to implement to understand

Powerful enough for use in large programs

Page 8: Summary of previous weeks

program Radioactive_Decay!----------------------------------------------------------------------------! This program calculates the amount of a radioactive substance that ! remains after a specified time, given an initial amount and its ! half-life. Variables used are:! InitalAmount : initial amount of substance (mg)! HalfLife : half-life of substance (days)! Time : time at which the amount remaining is calculated (days)! AmountRemaining : amount of substance remaining (mg)!! Input: InitialAmount, HalfLife, Time! Output: AmountRemaining!-----------------------------------------------------------------------------

implicit none real :: InitialAmount, HalfLife, Time, AmountRemaining

! Get values for InitialAmount, HalfLife, and Time.

print *, "Enter initial amount (mg) of substance, its half-life (days)" print *, "and time (days) at which to find amount remaining:" read *, InitialAmount, HalfLife, Time ! Compute the amount remaining at the specified time. AmountRemaining = InitialAmount * 0.5 ** (Time / HalfLife)

! Display AmountRemaining. print *, "Amount remaining =", AmountRemaining, "mg"

end program Radioactive_Decay

Page 9: Summary of previous weeks

2.1 Data types

There are five basic data types in fortran 1) INTEGER 2) REAL 3) COMPLEX 4) CHARACTER 5) LOGICAL

Numerical-data types

Strings of characters

Logical data values

Non-numericaldata types

Page 10: Summary of previous weeks

Arithmetic operators in F

Operator Meaning+ Addition- Substraction* Multiplication/ Division** Exponentiation (or ‘rising the power of’)

Page 11: Summary of previous weeks

Arithmetic operator priorities

Operator Priority** High* and / Medium+ and - Low

Examples: W=c/d*b

Total=2**3+5*2=18 W=x+z-y

Page 12: Summary of previous weeks

Names & Declarations

A data object is a constant that never changes or a variable that can change during program execution.

Data object may have names. For example, Average, X, Y, Einstein, or Potential_Energy.

Names in a program must conform to 3 rules:1) A name may contain up to 31 letters, digits, and underscore

characters2) The first character of a name must be a letter3) Imbedded blank characters are not permitted in a name

IMPORTANT: keywords such as program, write, and end are not actually names

Page 13: Summary of previous weeks

Type Declarations Every variable and named constant must appear in a type

declaration The type of a Fortran variable determines the type of value

that may be assigned to that variable. In every F program, the specification statement implicit none

must immediately follow the program statement

program Researchimplicit none

...

end program Research

Type name ::List of names

Page 14: Summary of previous weeks

Type Declarations

implicit noneinteger :: Counts, Loop_Indexreal :: Current, Resistance, Voltage

Names defined as part of the F language, including keywords and intrinsic function names (such as sin, tan, abs, etc.), must be written in lower case. Names that you invent can use any combination of upper and lower case, but each name must be written consistently.

Page 15: Summary of previous weeks

Type properties: Kind & Length

Kind : A variable of any numerical type has a kind type parameter, which designates a subtype or variant of the type.

Each type has a default computer representation For each numerical data type, F defines a set of integers to be used

as kind type parameter values (i.e., the number 4 for real representation, number 8 for the higher-precision variant)

Length : A variable of character data type has a string length property.

A character type declaration must specify string length

A type declaration appears in parentheses after the type name. If no

kind parameter is specified, F selects the default computer representa-

tion Type name (Type properties) :: List of names

Page 16: Summary of previous weeks

Constants The name of a constant looks like the name of a

variable and it must be listed in the type declaration The keyword parameter designates a named constant Houdini Principle: Don’t use magic numbers

use a named constant rather than a explicit constant give always explanations ( use !)

Page 17: Summary of previous weeks

Declaration for a Named Constant

Declaration of a named constant is as follows: Type name, parameter :: List of initializationswhere each list item has the form Name = Value definitionThe value definition is an explicit constant.Examples: integer, parameter :: LENGTH=12 real, parameter :: PLANK=6.6260755e-34, PI=3.141593 real, parameter :: GRAVITY=9.807, AVAGADRO=6.0221367e23, & twoPI=2.0*PI integer, parameter :: A=20, HIGH=30, NEON=67 character (Len=2), parameter :: units=”Cm”

ATTENTION: Continuation line with ampersand symbol.

Page 18: Summary of previous weeks

Simple Input & OutputRead (unit = *, fmt = *) Input List

Write (unit = *, fmt = *) Output List

An asterisk as the unit in a read or write control list designates the default input device (the keyboard) or the default output device (The terminal screen)

An asterisk as the format designates list-directed formatting. Input data values for on-line list-directed input are entered at the computer keyboard in free form. Consecutive values must be separated by blanks.

For example: read (unit = *, fmt = *) Radii, I, Current, Top can be entered as 9.75 10 15.32 765.3

Page 19: Summary of previous weeks

Mixed-mode assignment

Assume that, b is a real variable whose value is 100.0, while c and d are

integers having the values 9 and 10, respectively. a = b*c/d result is 90.0 a = c/d*b a gets 0 value.

This phenomenon is known as integer division

Page 20: Summary of previous weeks

Program style and design

A program must be correct, readable, and understandable. The basic principles for developing a good program are as follows:

1) Programs cannot be considered correct until they have been validated using test data.

2) Programs should be well structured3) Each program unit should be documented4) A program should be formatted in a style that enhances

its readability5) Programs should be readable and understandable6) Programs should be general and flexible

Page 21: Summary of previous weeks

Fundamental types of numbers

Integers Whole numbers (positive/negative/zero) Examples:

195234567878901230-2334567

Typical range on a 32-bit computer-2 x 109 to +2 x 109

Page 22: Summary of previous weeks

Fundamental types of numbers

Reals+/- xxx.yyyyy

xxx integer partyyyyy fractional part

A better representation: Sign: +/- Mantissa: a fraction between 0.1 and 1.0 Exponent: x 10e

- 0.923456 x 10-6 or -0.923456e-6

Page 23: Summary of previous weeks

real and integer variables

Variable declaration:type :: name

type :: name1, name2, … integer :: a, b, c real :: x, y, z

Page 24: Summary of previous weeks

List-directed input and output

read *, var_1, var_2, … only variables!

print *, item_1, item_2, … variables, constants, expressions, …

Value separators: Comma (,) Space Slash (/) End-of-line

Page 25: Summary of previous weeks

Named constants type, parameter :: name1=constant_expression1, …

real, parameter :: pi=3.1415926, pi_by_2 = pi/2.0

integer, parameter :: max_lines = 200

Page 26: Summary of previous weeks

Example

! Name : Dursun Zafer Seker! Tel : +90 (212) 285 3755 (office)! Address : ITU, Faculty of Civil Engg. 80626 Maslak, Istanbul! Purpose : Converts Celsius to Fahrenheit! Date : February 29, 2000! Comments:.....!program Cel_Fah real :: CEL, FAH print *, "Please Enter Celsius Temperature" read *, CEL FAH = 9.0*CEL/5.0+32.0 print*,"Celsius = ",CEL," Fahrenheit = ", FAHend program Cel_Fah

Page 27: Summary of previous weeks

Example

! Name : Dursun Zafer Seker! Address : ITU, Faculty of Civil Engg. 80626 Maslak, Istanbul!! Date : February 29, 2000! Comments:.....!program Sin_Cos_Tan real :: angle,S,C,T,RAD real, parameter :: PI = 3.1415926 print *, "Please Enter Value of Angle in degrees" read *, angle RAD = angle/(180.0/PI) S = sin(RAD) C = cos(RAD) T = tan(RAD) print*,"angle = ",angle," Sinx = ",S," Cosx = ",C," Tanx = ",Tend program Sin_Cos_Tan

Page 28: Summary of previous weeks

program list_directed_input_example!integersinteger::int_1, int_2, int_3real::real_1, real_2, real_3!initial valuesint_1=-1int_2=-2int_3=-3real_1=-1.0real_2=-2.0real_3=-3.0!read dataread*, int_1, real_1, int_2, real_2,int_3, real_3!print new valuesprint*, int_1, real_1, int_2, real_2,int_3, real_3end program list_directed_input_example

Example

Page 29: Summary of previous weeks

Seven Golden Rules

Always plan ahead

Develop in stages

Modularize

Keep it simple

Test throughly

Document all programs

Enjoy your programming

Page 30: Summary of previous weeks

Programs and modules

Main program unit

program name

use statements...Specification statements (for variables)...Executable statements (for calculations)...

end program name

Page 31: Summary of previous weeks

Modules

Programs for solving complex problems should be designed in a modular fashion.

The problem should be divided into simpler subproblems, so that the subprograms can be written to solve each of them.

Every program must include exactly one main program and may also include one or more modules.

Page 32: Summary of previous weeks

Modules

•Modules are a second type of program unit.

•The basic structure of a module is similar to the main program unit.

•The initial module statement of each module specifies the name of

that module based on the F language rules.

•A module unit ends with an end program statement incuding its

name.

•A module does not contain any executable statements.

•A module may contain any number of subprograms which are

seperated from the other statements by a contain statement.

Page 33: Summary of previous weeks

Module program unit

module name

use statements...Specification statements.

contains(Procedure definitions)

subprogram_1subprogram_2..subprogram_n

end module name

Page 34: Summary of previous weeks

Procedures

A special section of program which is, in some way, referred to whenever required, is known as a “procedure”. Programs

     can be written by the programmer     by some other person who allows the programmer to use them    can be a part of the F language itself (i.e. intrinsic procedures whose names are reserved words must always be written in lower case). Subprograms can also be categorized as  subroutines ( there are 5 intrinsic subroutines )  functions ( create only a single result ; there are 97 intrinsic functions available in F )

Page 35: Summary of previous weeks

Procedures

Procedures - origin “Write your own” (homemade) Intrinsic (built-in, comes with F )

sin(x), cos(x), abs(x), … Written by someone else (libraries)

Procedures (subprograms) – form Functions Subroutines

Page 36: Summary of previous weeks

Procedures

name (argument_1, argument_2, ...)

Examples:

a + b * log (c)

-b + sqrt ( b * b – 4.0 * a * c)

Page 37: Summary of previous weeks

ProceduresA) PROBLEM : A farmer has a triangular field which he wishes to sow with wheat.

Write a program that reads the lenghts of the 3 sides of the field (in meters) and the sowing density (in grams per square meters)

Print the number of 10 kilo bags of wheat he must purchase in order to sow the whole field.

B.) ANALYSIS : STRUCTURE PLAN of the PROBLEM

    read lenghts of the sides of the field ( a, b, c ) and calculate the area of the field

area = ( s (s-a)(s-b)(s-c) ) ½

2s = a + b + c

•        read the sowing density

•       calculate the quantity of wheat seed required

•       calculate the number of 10 kilo bags this represents

Page 38: Summary of previous weeks

C) SOLUTION

program wheat_sowing

! This program calculate quantity of wheat required to sow a triangular field

! Variable declarations

real : : a, b, c,s, area, density, quantity

integer : : num_bags

! read the lengths of the sides of the field

print *, “type the lengths of the 3 sides of the field in metres : “

read *, a, b, c

! calculate the area of the field

s = 0.5 * ( a + b + c )

area = sqrt( s * (s - a)*(s - b)*(s - c) )

! read sowing density

print *, “ What is the sowing density (gms/sq.m) ?”

read *, density

! calculate quantity of wheat and the number of 10 kilo bags

! round up more than 1 kg

quantity = density * area

num_bags = 0.0001 * quantity + 0.9

! print results

print *, “the area of the field is “, area,” sq. metres”

print *, “and “, num_bags,” 10 kilo bags will be required”

end program wheat_sowing

Page 39: Summary of previous weeks

Subprograms

Functions : Functions may, of course, be provided by the user and they are normally implemented by means of an F subprogram which is physically placed within a module as is explained in Modules.

 

On the other hand, very important principle which applies to all procedures in F is that the main program and any subprograms need never be aware of the internal details of any other program unit or subprograms .

A function subprogram can be called by

        the main program

        another subroutine subprogram

        another function

Page 40: Summary of previous weeks

Functions

function name (d1, d2, …) result(result_name)

Specifications part..

Execution part end function name Variables

Internal (local) variables Result variable (keyword result) Dummy argument (keyword intent(in))attribute

Page 41: Summary of previous weeks

Functions

function cube_root result(root)! A function to calculate the cube root of ! a positive real number! Dummy argument declaration

real, intent(in) :: x! Result variable declaration

real :: root! Local variable declaration

real :: log_x! Calculate cube root by using logs

log_x = log(x)root = exp(log_x/3.0)

end function cube_root

Page 42: Summary of previous weeks

Subroutinessubroutine roots (x, square_root, cube_root, fourth_root, & fifth_root)! Subroutine to calculate various roots of positive real! Number supplied as the first argument, and return them in! the second to fifth arguments

! Dummy argument declarations real, intent(in) :: x real, intent(out) :: square_root, cube_root, & fourth_root, fifth_root ! Local variable declaration real :: log_x ! Calculate square root using intrinsic sqrt square_root = sqrt(x) ! Calculate other roots by using logs log_x = log(x) cube_root = exp(log_x/3.0) fourth_root = exp(log_x/4.0) fifth_root = exp(log_x/5.0)end subroutine roots

Page 43: Summary of previous weeks

Subroutines

call name (arg1, arg2, …) intent(in), intent(out), intent(inout)

Page 44: Summary of previous weeks

Attributes

intent (in): the dummy argument only provides information to the procedure and is not allowed to change its value any way

intent (out): the dummy argument only returns information from the procedure to the calling program

intent (inout): the dummy argument provides

information in both directions

Page 45: Summary of previous weeks

Saving the values of local objects

Local entities within a procedure are not accessible from outside that procedure

Once an exit has been made, they cease to exist

If you want their values to ‘survive’ between calls, usereal, save :: list of real variables

real, save::a, b=1.23, c

İnteger, save::count=0

Page 46: Summary of previous weeks

Example

MAIN PROGRAM

program ……..

real : : Alpha, Beta, Gamma

.

.

Alpha = Fkt ( Beta, Gamma )

.

.

end program ……….

 

 

FUNCTION SUBPROGRAM

function Fkt ( x, y )

real : : Fkt

real : : x, y

Fkt = x ** 2 - 2.5 * y + 3.7 * y ** 2

x = 0.0

end function Fkt

Page 47: Summary of previous weeks

Example: Write a subprogram which calculates the cube root of a positive real number

MAIN PROGRAM

program test_cube_root

use maths

real : : x

print *, “Type a positive real number”

read *, x

Print *, “ The cube root of “,x,” is “, cube_root(x)

.

a = b * cube_root(x) + d

.

end program test_cube_root

Page 48: Summary of previous weeks

module maths

Public::cube_root

contains

function cube_root (x) result (root)

! a function to calculate the cube root of a positive real number

! Dummy arguments

real , intent (in) : : x

! Result variable declaration

real : : root

! Local variable declaration

real : : log_x

! Calculate cube root by using logs

log_x = log (x)

root = exp (log_x / 3.0)

function cube_root

end module maths