Summary of previous weeks - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Summary of previous weeks

Description:

reserved words must always be written in lower case). Subprograms can also be categorized as ... round up more than 1 kg. quantity = density * area. num_bags ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 49
Provided by: fpc6
Category:

less

Transcript and Presenter's Notes

Title: Summary of previous weeks


1
Summary of previous weeks
BIL 102 Introduction to Scientific
Engineering Computing
2
Course Contentents
  • Introduction to computing
  • Basic FORTRAN
  • Selective execuation
  • Repetitive execuation
  • Input/output
  • Programming with functions
  • Arrays, Data types, Files
  • Pointers and linked structures

3
Course WEB site
  • http//www3.itu.edu.tr/F90

Textbook
Programming in F T.M.R. Ellis and Ivor R.
Philips Several copies at the M.I.L.s Reserve
Section Photocopies available Fen-Edebiyat
printshop
4
Registration
5
How do we tell these days a computer what to do?
Source program (high level language)
Compiler
Object program (machine language)
6
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

7
The F language
  • F Fortran 90
  • Easy
  • to learn
  • to implement
  • to understand
  • Powerful enough for use in large programs

F
Fortran 77
Fortran 90
8
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
9
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
Non-numerical data types
Logical data values
10
Arithmetic operators in F
  • Operator Meaning
  • Addition
  • - Substraction
  • Multiplication
  • / Division
  • Exponentiation (or rising the power of)

11
Arithmetic operator priorities
  • Operator Priority
  • High
  • and / Medium
  • and - Low
  • Examples
  • Wc/db
  • Total235218
  • Wxz-y

12
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 characters
  • 2) The first character of a name must be a letter
  • 3) Imbedded blank characters are not permitted in
    a name
  • IMPORTANT keywords such as program, write, and
    end are not actually names

13
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 Research
  • implicit none
  • .
  • .
  • .
  • end program Research
  • Type name List of names

14
Type Declarations
  • implicit none
  • integer Counts, Loop_Index
  • real 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.

15
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

16
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 Dont use magic numbers
  • use a named constant rather than a explicit
    constant
  • give always explanations ( use !)

17
Declaration for a Named Constant
  • Declaration of a named constant is as follows
  • Type name, parameter List of
    initializations
  • where each list item has the form
  • Name Value definition
  • The value definition is an explicit constant.
  • Examples
  • integer, parameter LENGTH12
  • real, parameter PLANK6.6260755e-34,
    PI3.141593
  • real, parameter GRAVITY9.807,
    AVAGADRO6.0221367e23,
  • twoPI2.0PI
  • integer, parameter A20, HIGH30,
    NEON67
  • character (Len2), parameter
    unitsCm
  • ATTENTION Continuation line with ampersand
    symbol.

18
Simple Input Output
  • Read (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

19
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 bc/d
  • result is 90.0
  • a c/db
  • a gets 0 value.
  • This phenomenon is known as integer division

20
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 structured
  • 3) Each program unit should be documented
  • 4) A program should be formatted in a style that
    enhances its readability
  • 5) Programs should be readable and understandable
  • 6) Programs should be general and flexible

21
Fundamental types of numbers
  • Integers
  • Whole numbers (positive/negative/zero)
  • Examples
  • 1952
  • 3456787890123
  • 0
  • -2334567
  • Typical range on a 32-bit computer
  • -2 x 109 to 2 x 109

22
Fundamental types of numbers
  • Reals
  • /- xxx.yyyyy
  • xxx integer part
  • yyyyy 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

23
real and integer variables
  • Variable declaration
  • type name
  • type name1, name2,
  • integer a, b, c
  • real x, y, z

24
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

25
Named constants
  • type, parameter name1constant_expression1,
  • real, parameter pi3.1415926, pi_by_2 pi/2.0
  • integer, parameter max_lines 200

26
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..... ! prog
ram Cel_Fah real CEL, FAH print ,
"Please Enter Celsius Temperature" read ,
CEL FAH 9.0CEL/5.032.0 print,"Celsius
",CEL," Fahrenheit ", FAH end program
Cel_Fah
27
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 ",T end program
Sin_Cos_Tan
28
program list_directed_input_example!integersinte
gerint_1, int_2, int_3realreal_1, real_2,
real_3!initial valuesint_1-1int_2-2int_3-3
real_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
29
Seven Golden Rules
  • Always plan ahead
  • Develop in stages
  • Modularize
  • Keep it simple
  • Test throughly
  • Document all programs
  • Enjoy your programming

30
Programs and modules
  • Main program unit
  • program name
  • use statements
  • .
  • .
  • .
  • Specification statements (for variables)
  • .
  • .
  • .
  • Executable statements (for calculations)
  • .
  • .
  • .
  • end program name

31
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.
32
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.

33
Module program unit
  • module name
  • use statements
  • .
  • .
  • .
  • Specification statements
  • .
  • contains
  • (Procedure definitions)
  • subprogram_1
  • subprogram_2
  • .
  • .
  • subprogram_n

34
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 )
35
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

36
Procedures
  • name (argument_1, argument_2, ...)
  • Examples
  • a b log (c)
  • -b sqrt ( b b 4.0 a c)

37
Procedures
  • A) 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

38
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
39
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
40
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
41
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

42
Subroutines
  • subroutine 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)

43
Subroutines
  • call name (arg1, arg2, )
  • intent(in), intent(out), intent(inout)

44
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

45
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, use
  • real, save list of real variables

real, savea, b1.23, c Integer, savecount0
46
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
47
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
48
module maths Publiccube_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
Write a Comment
User Comments (0)
About PowerShow.com