Download presentation
Presentation is loading. Please wait.
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? Compiler Source program (high level language) 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 F Fortran 77 Fortran 90 Easy to learn to implement to understand Powerful enough for use in large programs
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 Logical data values Non-numerical data types
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: W=c/d*b Total=2**3+5*2=18 W=x+z-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: Don’t 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 :: 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.
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 = b*c/d result is 90.0 a = c/d*b 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 10 9 to +2 x 10 9
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 10 e - 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 :: name1=constant_expression1, … real, parameter :: pi=3.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:..... ! 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 = ", 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 !integers integer::int_1, int_2, int_3 real::real_1, real_2, real_3 !initial values int_1=-1 int_2=-2 int_3=-3 real_1=-1.0 real_2=-2.0 real_3=-3.0 !read data read*, int_1, real_1, int_2, real_2,int_3, real_3 !print new values print*, int_1, real_1, int_2, real_2,int_3, real_3 end 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 end module name
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) end subroutine roots
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, save::a, b=1.23, c İnteger, save::count=0
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 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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.