Programming For Nuclear Engineers Lecture 3 Basic Elements of Fortran

# Programming For Nuclear Engineers Lecture 3 Basic Elements of Fortran

## Programming For Nuclear Engineers Lecture 3 Basic Elements of Fortran

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. 1- Constants and Variables 1.1- Integer Constants and Variables 1.2- Real Constants and Variables 1.3- Character Constants and Variables 1.4-Default and Explicit Variable Typing 1.5- Keeping Constants Consistent in a Program 2- Assignment Statements and Arithmetic Calculations 2.1- Integer Arithmetic 2.2- Real Arithmetic 2.3- Hierarchy of Operations 2.4- Mixed-Mode Arithmetic 3- Intrinsic Functions 4- Initialization of Variables 5- The IMPLICIT NONE Statement 6- Examples

2. 1- Constants and Variables A Fortran Constant is a data object that is defined before a program is executed, and that does not change value during the execution of the program. When a Fortran compiler encounters a constant, it places the value of the constant in a known location in memory, and then references that memory location whenever the constant is used in the program. A Fortran Variable is a data object that can change value during the execution of a program. (The value of a Fortran variable may or may not be initialized before a program is executed.) When a Fortran compiler encounters a variable, it reserves a known location in memory for the variable, and then references that memory location whenever the variable is used in the program.

3. Each Fortran variable in a program unit must have a unique name. The variable name is a label for a specific location in memory that is easy for humans to remember and use. Fortran 95 names may be up to 31 characters long (Fortran 2003 names can be up to 63 characters long), and may contain any combination of alphabetic characters, digits, and the underscore (_) character. However, the first character in a name must always be alphabetic. The following examples are valid variable names: time distance z123456789 I_want_to_study

4. The following examples are invalid variable names: this_is_a_very_long_variable_name(Illegal in Fortran 95-too long; legal in Fortran 2003.) this_is_a_very_very_very_very_very_very_very_very_long_variable_ name (Name is too long for Fortran 2003.) 3_days (First character is a number.) A\$ (\$ is an illegal character.) It is so important to include a data dictionary in the header of any program that you write. A data dictionary lists the definition each variable used in a program. The definition should include both a description of the contents of the item and the units in which it is measured.

5. There are five intrinsic or “built-in” types of Fortran constants and variables. Three of them are numeric (types INTEGER, REAL, and COMPLEX), one is logical (type LOGICAL), and one consists of strings of characters (type CHARACTER). The simplest forms of the INTEGER, REAL, and CHARACTER data types will be discussed in this lecture. The other types of Fortran constants and variables will be discussed later.

6. 1.1- Integer Constants and Variables An Integer Constants is any number that does not contain a decimal point. If a constant is positive, it may be written either with or without a + sign. No commas may be embedded within an integer constant. The following examples are valid integer constants: 0 -999 123456789 +17 The following examples are not valid integer constants|: 1,000,000 (Embedded commas are illegal.) -100. (If it has a decimal point, it is not an integer constant!)

7. An Integer Variable is a variable containing a value of the integer data type. Constants and variables of the integer data type are usually stored in a single word on a computer. Since the length of a word varies from 16 bits up to 64 bits on different computers, the largest integer that can be stored in a computer also varies. The largest and smallest integers that can be stored in a particular computer can be determined from the word size by applying the following equations: Smallest integer value = Largest integer value = For a 32 bits (4-byte) integer, the smallest and largest possible values are -2,147,483,648 and 2,147,483,647 respectively.

8. 1.2- Real Constants and Variables The real data type consists of numbers stored in real or floating-point format. Unlike integers, the real type can represent numbers with fractional components. A real constant is a constant written with a decimal point. It may be written with or without an exponent. If the constant is positive, it may be written either with or without a + sign. No commas may be embedded within a real constant. Real constants may be written with or without an exponent. If used, the exponent consists of the letter E followed by a positive or negative integer, which corresponds to the power of 10 used when the number is written in scientific notation. Also the mantissa of the number should contain a decimal point. The following examples are not valid real constants: 1,000,000. Embedded commas are illegal 111E3 A decimal point is required in the mantissa -12.01E1.5 Decimal points are not allowed in exponents

9. A real variable is a variable containing a value of the real data type. A real value is stored in two parts: the mantissa and the exponent. The number of bits allocated to the mantissa determines the precision of the constant, while the number of bits allocated to the exponent determines the range of the constant. All Fortran 95/2003 compilers support real numbers with more than one length. By selecting the proper kind, it is possible to increase the precision and range of a real constant or variable. 1.3 Character Constants and Variables The character data type consists of strings of alphanumeric characters. A character constant is a string of characters enclosed in single (’) or double (”) quotes. The minimum number of characters in a string is 1, while the maximum number of characters in a string varies from compiler to compiler. The characters between the two single or double quotes are said to be in a character context. Any characters representable on a computer are legal in a character context, not just the characters forming the Fortran 95 or 2003 character set.

10. The following are valid character constants: ‘This is a lecture’ ‘{^}’ “3.141593” The following are not valid character constants: This is a lecture ‘This is a lecture” “Try to study.’ The character string containing an apostrophe, could be represented by two consecutive single quotes and can be surrounded by single or double quotes, for example: The string “Man’s best friend” could be written as: ‘Man”s best friend’ or “Man”s best friend”

11. 1.4 Default and Explicit Variable Typing It is easy to see whether a constant is INTEGER, REAL, or CHARACTER. But with variables, the situation is not so clear. There are two possible ways in which the type of a variable can be defined: default typing and explicit typing. Any variable names beginning with the letters I, J, K, L, M, or N are assumed to be of type INTEGER. Any variable names starting with another letter are assumed to be of type REAL. No variable names are of type CHARACTER by default. The type of a variable may also be explicitly defined in the declaration section at the beginning of a program, the following examples explain this: INTEGER::var1[,var2,var3,…] REAL::var1[,var2,var3,…] These nonexecutable statements are called type declaration statements. They should be placed after the PROGRAM statement and before the first executable statement in the program.

12. Allcharacter variables must be explicitly typed, using the CHARACTER type declaration statement. CHARACTER(len=<len>)::var1[var2,var3,…] Where <len> is the number of characters in the variables. And the portion of the statement (len=<len>) is optional. If the parentheses are entirely absent, then the character variables declared by the statement have length 1. CHARACTER(len=10)::first,last CHARACTER::initial CHARACTER(15)::id

13. 1.5 Keeping Constants Consistent in a Program The best way to achieve consistency and precision throughout a program is to assign a name to a constant, and then to use that name to refer to the constant throughout the program. Assigning meaningful names to constants improves the overall readability of our programs. By using the PARAMETER attribute of a type declaration statement, we could create Named constants. In general: type,PARAMETER::name=value[name2=value2,…] examples: REAL, PARAMETER::PI=3.1415926 CHARACTER,PARAMETER::ERROR_MESSAGE=‘Unknown error!’

14. 2- Assignment Statements and Arithmetic Calculations Calculations are specified in Fortran with an assignment statement, whose general form is: variable_name=expression Equal sign store the value of expression into location variable name. and it is called the assignment operator. The following example show the case: i=i+1 In Fortran it means: take the current value stored in variable i, add one to it, and store the result back into variable i. Rules: 1- No two operators may occur side by side. 2- Implied multiplication is illegal in Fortran. 3- Parentheses may be used to group terms whenever desired.

15. 2.1 Integer Arithmetic Arithmetic involving only integer data, and it always produces an integer result. When an expression involves division, and the division is not itself an integer, the computer automatically truncates the fractional part of the answer. So you should only use integers arithmetic for things that are intrinsically integer in nature, such as counters and indices. And they should not be used to calculate real-world quantities that vary continuously, such as distance, speed, time, etc. 2.2 Real Arithmetic Real arithmetic (or floating-point arithmetic) is arithmetic involving real constants and variables. Real arithmetic always produces a real result that is essentially what we would expect. For example, real arithmetic produces the following results:

16. Because of the finite word length of a computer, some real numbers cannot be represented exactly. 2.3 Hierarchy of Operations To make the evaluation of expressions unambiguous, Fortran has established a series of rules governing the hierarchy or order in which operations are evaluated within an expression, which is: 1- The contents of all parentheses are evaluated first, starting from the innermost parentheses and working outward. 2- All exponentials are evaluated, working from right to left. 3- All multiplications and divisions are evaluated, working from left to right. 4- All additions and subtractions are evaluated, working from left to right.

17. 2.4 Mixed-Mode Arithmetic Expressions containing both real numbers and integers are called mixed-mode expressions, and arithmetic involving both real numbers and integers is called mixed-mode arithmetic. When a mixed-mode operation is encountered, Fortran converts the integer into a real number, and then performs the operation to get a real result. The automatic mode conversion does not occur until a real number and an integer both appear in the same operation, the following examples show this case: Integer expression: 5/2 is evaluated to be 2 (integer result) Real expression: 5./2. is evaluated to be 2.5 (real result) Mixed-mode expression: 5./2 is evaluated to be 2.5 (real result) sern=2.25+9/2 is evaluated to be 3 if sern is an integer Fortran 95/2003 includes five type conversion functions that allow us to explicitly control the conversion between integer and real values, as described in the table:

18. To understand the differences amongst theses functions, let’s consider the real numbers 3.9995 and -3.9995 . The results of each function with these inputs is shown below:

19. 3- Intrinsic Functions The Fortran 95/2003 language has mechanism to support both the very common functions (used in many different technical disciplines, such as trigonometric functions), and the less common functions (specific to a single problem or a small number of problems, such as Bessel functions). Many of the most common ones are built directly into the Fortran language. They are called intrinsic functions. A Fortran function takes one or more input values, and calculates a single output value for them. The output of a function is a single number, logical value, or character string. When a common function appears in a Fortran statement, the arguments of the function are passed to a separate routine that computes the result of the function, and then the result is used in place of the function in the original calculation

20. 4- Initialization of Variables: Uninitialized variables can present a serious problem, so we must avoid them by always initializing all of the variables in our programs. Three techniques are available to initialize variables in a Fortran program: 1- Assignment statements: PROGRAM init_1 INTEGER::i i=1 WRITE(*,*)i END PROGRAM init_1 2- READ statements: PROGRAM init_2 INTEGER::i READ(*,*)i WRITE(*,*)i END PROGRAM init_2 3- Initialization in type declaration statements: type::var1=value,[var2=value,…]

21. 5- The IMPLICIT NONE Statement It is a very important nonexecutable statement, and it should appear after the PROGRAM statement and before any type declaration statements. When the IMPLICIT NONE statement is included in a program, the programmer must explicitly declare the type of every variable in the program. IMPLICIT NONE statement have several advantages to using: 1- explicit error message flagging the problem will appear at compilation time, 2- makes the code more maintainable as the size of a programming project increases, or if the program must be modified.

22. 6- Examples 1- A radioactive isotope of an element is a form of the element that is not stable. Instead, it spontaneously decays into another element over a period of time. Radioactive decay is an exponential process. If Q0 is the initial quantity of a radioactive substance at time t = 0, then the amount of that substance that will be present at any time t in the future is given by: Q(t) = Q0 e-λt (1) Because radioactive decay occurs at a known rate, it can be used as a clock to measure the time since the decay started. If we know the initial amount of the radioactive material Q0 present in a sample, and the amount of the material Q left at the current time, we can solve for t in equation (1) to determine how long the decay has been going on. The resulting equation is: t = -(1/λ)log( Q/Q0 ) (2) Use equations (1) and (2) to write a program that reads the percentage of carbon14 remaining in a sample, calculates the age of the sample from it, and prints out the result with proper units (λ = 0.00012097/year).

23. Solution: We should take into account that our program must perform the following steps: 1- Prompt the user to enter the percentage of carbon 14 remaining in the sample. 2- Read in the percentage. 3- Convert the percentage into the fraction Q/Q0 . 4- Calculate the age of the sample in years, using equation (2) 5- Write out the result, and stop. PROGRAM C14_date ! !Aim: !To calculate the age of an organic sample from the !percentage of the original carbon 14 remaining in the !sample. IMPLICIT NONE !Data dictionary: declare constants REAL,PARAMETER::LAMDA=0.00012097 ! The radioactive decay !constant of carbon 14. !in units of 1/years.

24. !Data dictionary: declare variable types, definitions, !&units REAL::age !The age of the sample (years) REAL::percent !The percentage of carbon 14 remaining at !the time of the measurement (%) REAL::ratio !The ratio of the carbon 14 remaining at !the time of the measurement to the !original amount of carbon 14 (no units) WRITE(*,*)’Enter the percentage of carbon 14 remaining:’ READ(*,*)percent WRITE(*,*)’The remaining carbon 14=‘, percent,’%.’ ratio=percent/100. !Convert to fractional ratio age=(-1.0/LAMDA)*log(ratio) !Get age in years WRITE(*,*)’The age of the sample is’,age,’years.’ END PROGRAM c14_date

25. For half of the carbon 14 to disappear ( half-life of carbon 14), we will have the output: Enter the percentage of carbon 14 remaining: 50. The remaining carbon 14 = 50.000000%. The age of the sample is 5729.910000 years. Which is agree with the true value of 5730 years.