1 / 101

Summary of previous weeks

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

cantrellj
Download Presentation

Summary of previous weeks

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Summary of previous weeks BIL 102 Introduction toScientific & 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. 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

  4. 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

  5. Arithmetic operators in F OperatorMeaning + Addition - Substraction * Multiplication / Division ** Exponentiation (or ‘rising the power of’)

  6. Arithmetic operator priorities OperatorPriority ** High * and / Medium + and - Low Examples: W=c/d*b Total=2**3+5*2=18 W=x+z-y

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

  8. 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.

  9. 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

  10. 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 !)

  11. 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.

  12. 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

  13. Mixed-mode assignment Assume that, b is a real variable whose value is 100.0, while c and d are integershaving 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

  14. 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

  15. 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

  16. Fundamental types of numbers • Reals +/-xxx.yyyyy xxxinteger 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

  17. real and integer variables • Variable declaration: type :: name type :: name1, name2, … • integer :: a, b, c • real :: x, y, z

  18. 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

  19. Named constants • type, parameter :: name1=constant_expression1, … real, parameter :: pi=3.1415926, pi_by_2 = pi/2.0 integer, parameter :: max_lines = 200

  20. 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

  21. Seven Golden Rules • Always plan ahead • Develop in stages • Modularize • Keep it simple • Test throughly • Document all programs • Enjoy your programming

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

  23. 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.

  24. 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.

  25. Module program unit modulename use statements . . . Specification statements . contains (Procedure definitions) subprogram_1 subprogram_2 . . subprogram_n end modulename

  26. 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

  27. Procedures name (argument_1, argument_2, ...) Examples: • a + b * log (c) • -b + sqrt ( b * b – 4.0 * a * c)

  28. Functions • functionname (d1, d2, …)result(result_name) Specifications part . . Execution part • end functionname • Variables • Internal (local) variables • Result variable (keyword result) • Dummy argument (keyword intent(in)) attribute

  29. 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

  30. 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

  31. Subroutines • call name (arg1, arg2, …) • intent(in), intent(out), intent(inout)

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

  33. 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

  34. Example MAIN PROGRAM program …….. real : : Alpha, Beta, Gamma . . Alpha = Fkt ( Beta, Gamma ) . . end program ………. FUNCTION SUBPROGRAM functionFkt ( x, y ) real : : Fkt real : : x, y Fkt = x ** 2 - 2.5 * y + 3.7 * y ** 2 x = 0.0 end function Fkt

  35. 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

  36. module maths Public::cube_root contains functioncube_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

  37. Controlling the flow of your program In everyday life we frequently encounter a situation which involves several possible alternative courses of action, requiring us to choose one of them based on some decision-making criteria. The ability of a program to specify how these decisions are to be made is one of the most important aspects of programming.

  38. Choice and decision-making EXAMPLE : Q: How do I get to Budapest from Vienna ? A : It depends how you want to travel : * if you are in hurrythen you should fly from Schwechat airport in Vienna to Ferihegy airport in Budapest * but ifyou are a romantic or like trainsthen you should take the Orient Express from Südbahnhof to Budapest’s Keleti palyudvar * but ifyou have plenty of timethen  you can travel on one of the boats which ply along the Danube * otherwise you can always go by road

  39. Choice and decision-making F provides a very similar construction for this decision-making problem as can be seen below : If criterion 1 then action 1 but if criterion 2 then action 2 but if criterion 3 then action 3 otherwise action 4

  40. Choice and decision-making if (criterion_1) then action_1 else if (criterion_2) then action_2 else if (criterion_3) then action_3 else action_4 endif

  41. Logical variables and expressions Logical variables + logical constants + logical operators Decision criterion in F language depends upon whether assertion is “true” or “false”, which are called logical variables and are declared as follows : logical : : var_1, var_2, var_3 In F language we can simply write these logical values enclosed between dots : .true. .false.

  42. logical variables • logical :: var_1, var_2, … • Logical valued functions functionname(arg1, …) resultlogical_variable logical :: logical_variable

  43. Logical (relational) operators An assertion or expression which can take one of the local variables “true” and “false”, is called a logical expression. The simplest forms of logical (relational) expressions are those expressing the relationship between 2 numeric values as, a < b less than a <= b less than or equal to a > b greater than a >= b greater than or equal a == b equal a /= b not equal

  44. Logical operators L1 L2 L1 .or. L2 L1 .and. L2 true true true true true false true false false true true false false false false false

  45. Examples • (a<b) .or. (c>d) • (x<=y) .and. (y<=z) • .not. (a<b) .eqv. (x<y) • a<b .neqv. x<y INVALID EXPRESSIONS I == 1.or.2(A.and.B) /= 0.0 x > 0.0 .and. > 1.0 0.0 < x < 1.0

  46. The if construct In the simplest selection structure, a sequence of statements (called a block of statements) is executed or bypassed depending on whether a given logical expression is true or false. If the logical expression is “true”, then the specified sequence of statements is executed ; otherwise it is bypassed. In either case, execution continues with the statement in the program following the “end if” statement. if ( logical_expression ) then statement sequence end if

  47. The if construct EXAMPLE : if ( x >= 0.0 ) then y = x * x z = sqrt (x) end if On the other hand, a general form of an if – construct has the following form: if ( logical_expression ) then statement_sequence_1 else statement_sequence_2 end if

  48. The if construct A typical structure for an general if – construct can be seen below : if (logical expression) then block of F statements else if (logical expression) then block of F statements else if (logical expression) then block of F statements else block of F statements endif

  49. Simple if construct if (logical expression) then block of F statements endif

  50. PROBLEM : A function subprogram which returns the cube root , is needed to write down. function cube_root (x) result (root) ! This function program calculates the cube rootof any real number ! Dummy argument and result declarations real, intent (in) : :x real : : root !eliminate the zero case if ( x == 0.0 ) then root = 0.0 ! calculate the cube root by using logsnegative argument else if ( x < 0.0 ) then root = - exp ( log (-x) / 3.0 ) ! positive argument else root = exp ( log (x) / 3.0 end if end function cube_root

More Related