SlideShare a Scribd company logo
Introduction To Fortran 95 And Numerical
Computing A Jumpstart For Scientists And
Engineers Adrian Sandu download
https://ebookbell.com/product/introduction-to-fortran-95-and-
numerical-computing-a-jumpstart-for-scientists-and-engineers-
adrian-sandu-28374602
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Introduction To Programming With Fortran With Coverage Of Fortran 90
95 2003 2008 And 77 2nd Edition Ian Chivers
https://ebookbell.com/product/introduction-to-programming-with-
fortran-with-coverage-of-fortran-90-95-2003-2008-and-77-2nd-edition-
ian-chivers-2521034
Introduction To Programming With Fortran With Coverage Of Fortran 90
95 2003 2008 And 77 3rd Edition Ian Chivers
https://ebookbell.com/product/introduction-to-programming-with-
fortran-with-coverage-of-fortran-90-95-2003-2008-and-77-3rd-edition-
ian-chivers-5234568
Introduction To Programming Using Fortran 9520032008 Version 3051 Ed
Jorgensen
https://ebookbell.com/product/introduction-to-programming-using-
fortran-9520032008-version-3051-ed-jorgensen-10466018
Introduction To Modern Fortran For The Earth System Sciences 1st
Edition Dragos B Chirila
https://ebookbell.com/product/introduction-to-modern-fortran-for-the-
earth-system-sciences-1st-edition-dragos-b-chirila-4974234
Introduction To Programming With Fortran 4th Edn Ian Chivers Jane
Sleightholme
https://ebookbell.com/product/introduction-to-programming-with-
fortran-4th-edn-ian-chivers-jane-sleightholme-49848242
Introduction To Programming With Fortran Ian D Chivers Bsc Pgced
https://ebookbell.com/product/introduction-to-programming-with-
fortran-ian-d-chivers-bsc-pgced-4239444
Introduction To Programming With Fortran 4th Ian Chivers Jane
Sleightholme
https://ebookbell.com/product/introduction-to-programming-with-
fortran-4th-ian-chivers-jane-sleightholme-7164316
Introduction To Programming With Fortran Ian Chivers Jane Sleightholme
https://ebookbell.com/product/introduction-to-programming-with-
fortran-ian-chivers-jane-sleightholme-59265710
Introduction To Computational Economics Using Fortran Hans Fehr Fabian
Kindermann
https://ebookbell.com/product/introduction-to-computational-economics-
using-fortran-hans-fehr-fabian-kindermann-10920622
Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists And Engineers Adrian Sandu
Lecture Notes
Introduction to Fortran 95 and Numerical Computing
A Jump-Start for Scientists and Engineers
Adrian Sandu
Computer Science Department, Michigan Technological University
Reproduction of (parts of) this document is permissible only with author's consent.
August 23, 2001
2 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
Acknowledgements
The present lecture notes are based in part on the following excellent books:
Fortran 90 Programming" by Ellis, Philips and Lahey, Addison-Wesley publishing company, 1994;
Fortran 90 Course Notes" by A.C. Marshall, U. Liverpool, 1997;
Elementary numerical analysis" by K.E. Atkinson, 2nd edition, John Wiley & Sons, Inc, 1993.
Contents
1 A quick tour of Fortran 95 5
2 The Building Blocks of a Fortran Application 23
3 More on Flow Control 41
4 Computer Representation of Numbers and Computer Arithmetic 47
5 Applications Part I. 77
6 Intrinsic Functions 83
7 Input and Output. 89
8 Arrays 99
9 More on Procedures 115
10 Parametrised Intrinsic Types 129
11 Derived Types 133
12 Pointers and Targets 137
13 Elements of object-oriented programming 149
14 Code Performance 151
15 Linear Systems of Algebraic Equations 157
16 Linear Least Squares 175
3
4 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
17 Nonlinear Equations 181
18 Polynomial Interpolation 189
19 Numerical Integration 191
20 Piecewise Polynomial Interpolation. Splines. 197
21 Taylor Polynomials 207
Chapter 1
A quick tour of Fortran 95
1.1 Program Form
The main program unit begins with the keyword program (optional), followed by the program name (also
otional); it ends with the keyword end (required), followed by program Name Prog (optional).
program <name>
declarations
executable code
end [ program <name> ]
Open a le hello.f90. Type the following hello world" program:
! my rst Fortran program
program hello
print , 'Hello World!'
end program hello
Compile it with f90 hello.f90. Run the resulting code with a.out.
1.2 Free vs. Fixed Formats
In Fortran 95 the code layout is obeys the following rules, which describe the free source form.
 statements can begin in any column;
 multiple statements on a line are allowed; they have to be separated by semicolon ;
 an exclamation mark ! in any column is the beginning of a comment; the rest of the line is ignored
by the compiler;
 a statement can be continued on the following line by appending a  sign on the current line.
For example, the above code fragment could be written in free source form as
5
6 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
! This is free form
temp = x; x = y; y = temp ! Swap x and y
write(6,) 'x and y are =', 
x,y ! Print x and y
For back-compatibility with Fortran 77, Fortran 90 accepts a  xed source form. In short, the xed
source form requirements are:
 all lines of code start in the 7th
(or higher) column; the rst 6 columns are reserved for labels, contin-
uation characters, etc.
 each statement is written on a separate line (i.e., statements are separated by newlines); a statement
can be continued on the next line by writing (any) character in the 5th
column of the new line;
 comment lines start with a C in the rst column.
Fixed format was born in 1950's, when each line of code was punched on a paper card (punched card). For
debugging and maintaining the code it was clearly easier to have one statement per card. When running,
a punched card had to be aligned, checked if it is a new statement or a continuation of the last, if it is a
comment, etc. - lots of information stored in the rst 6 columns. (A million-line code, quite common today,
on punched cards, needed a truck to be carried from one computer to another).
For example, a fragment of a Fortran 90 program in xed source form (in fact, Fortran 77 program) can
be:
C This is xed form
C Swap x and y
temp = x
x = y
y = temp
C Print x and y
write(6,) 'x and y are =',
 x,y
Our compiler (f90) will consider the program to be in xed source format if the source le has the
extension  .f (for example, my program.f). The compiler will consider the program to be in free source
format if the source le has the extension  .f90 (for example, my program.f90). Note that a free format
source in a .f le may result in compilation errors.
1.3 Declaration of Variables
1.3.1 Memory Organization. Variables
Discuss how memory is organized
Variables correspond to storage locations in memory. They are denoted by identi ers, which obey the
following restrictions:
 contain up to 31 characters;
 the rst character must be a letter;
 names are case-insensitive (no distiction between upper and lower case).
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 7
At the beginning of the program, we declare the types of the variables. Declarations reserve the necessary
number of bytes in memory and bind the variable name (identi er) to the address of the reserved memory
space; the content of the reserved bytes will hold the variable's value. There are 6 intrinsic (default) data
types in Fortran: character, logical, integer, real (single precision), double precision and complex. The last
four types are re erred to as numeric data types.
1.3.2 Integers.
Declaration:
integer I, J, K or
integer :: I, J, K
An integer can be declared and initialized with
integer :: I = 1
Normally, when the program is loaded in memory, the contents of the declared variables are unde ned (some
compilers may set them to 0 by default). With initialization, the content of the variables when loading is
set to the prescribed values.
An integer constant (whose value cannot be changed later in the program) can be declared with
integer MAXIMUM
parameter (MAXIMUM=340)
or with
integer, parameter :: MAXIMUM=340
The plain form of declaration, and the two-statement parameter declaration come from F77, and is legal
in F90 also. The double colon :: form is speci c to F90. Note that we have to use the double colon
form whenever more than one attribute is given for the variable (e.g., when is integer and parameter, i.e.
constant) or when the variable is initialized.
1.3.3 Characters.
Declaration:
character C or
character :: C
For a string of characters, we can specify the length and (optionally) initialize it as
character(len=7) :: LOGIN
Again we see that, if we want to specify more than one attribute (here, character and length) the double
colon form is needed.
We can have constant (PARAMETER) characters/strings, in which case we use the declaration
character(len=8), parameter :: LOGIN=johndoe
8 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
(the F77 two-statement form is also acceptable). Here the initialization value is 6-character long, so it will
be padded by 2 blanks to t the declared length. Similarly, if the initialization value was too long, it would
have been truncated to the declared length.
Alternatively, we may let the character variable assume the length of the initialization string with
character(len=), parameter :: LOGIN=johndoe, PASSWORD=michigantech
Here LOGIN will be 7-character, and PASSWORD 12-character long.
The following equivalent form of declaration is also accepted (for back-compatibility with F77):
character8 :: LOGIN
The LEN attribute can be overriden by a  attribute in a string declaration as follows:
character(len=8) :: LOGIN, PASSWORD12
Here LOGIN is a string of 8 characters, but PASSWORD is a string of 12 characters.
Note that a string is a scalar; in particular it is NOT an array of characters. For example, it is possible
to declare a 1010 matrix whose elements are 6-character long strings:
character(len=6), dimension(10,10) :: A
A string can be split accross lines by adding an ampersand  both at the end of the current line and at the
beginning of the next. For example
michig
nantech
1.3.4 Reals.
The declarations
real X, Y, PI or
real :: X, Y, PI
state that X, Y and PI are single precision oating point variables.
A real parameter (whose value cannot be changed subsequently) may be declared with
real PI
parameter (PI=3.141592)
or with
real, parameter :: PI=3.141592
The double colon form is needed for more than one attribute (see above), or for declarations plus initial-
izations
real :: X = 21.5g
Application: circle area and perimeter.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 9
program rst
implicit none ! disable implicit d.
real::R,Pi,a,p
Pi=3.1415926
print, 'Please give radius:'
read, R
a=PiR !  is exponentation
p=2.0PiR
print, 'Area=',a,' Perimieter=',p
end program rst
1.3.5 Double Precision.
The declarations
double precision X, Y, PI or
double precision :: X, Y, PI
state that X, Y and PI are double precision oating point variables. A similar discussion as for REAL type
holds.
1.3.6 Complex
Fortran allows for complex numbers also. They are declared as
complex Z, W or
complex :: Z, W
A Fortran complex variable is (and is stored as) a pair of real (single precision oating point) variables (the
real and the imaginary part, of course). For example, to declare and initialize the complex constant 2 + 3i
we use
complex, parameter :: Z=(2.0,3.0)
1.3.7 Logical.
Logical (Boolean) variables are declared as
logical Q, P or
logical :: Q, P
They can take only (one of) two possible values: true or false (written, in Fortran notation, .TRUE. and
.FALSE.). A declaration with initialization may look like
logical :: Q=.TRUE., P=.FALSE.
10 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
1.3.8 General Form of Declarations
The general form a F90 declaration is
htypei[;hattribute listi] :: 
[;hvariablei[= hvaluei]]
 attribute list  contains attributes like PARAMETER, SAVE, INTENT, POINTER, TARGET, DI-
MENSION, etc. Any object may be given any number of attributes, provided they are compatible with each
other.
1.3.9 Implicit declarations
In Fortran implicit declarations are allowed. Suppose we did not declare the variables I, J, X, Y but used
them somewhere in the program. The Fortran compiler will not complain; rather, it will automatically
declare I, J as integers and X, Y as reals. The rule is that undeclared variables which have the rst letter
I, J, K, L, M or N are considered INTEGER-s, and undeclared variables which start in A through H and O
through Z are considered REAL-s. The automatic declarations based on implicit types are called implicit
declarations. Some fourty years ago programmers found it cumbersome to explicitly declare all the variables
all the time !
In F90 implicit declarations are permitted, but undesirable. In general, their use is a very bad program-
ming habit, as it can mask programming errors, and can negatively impact future software development and
maintainance. For example, a misspelling of a variable name will result in a new variable declaration, which
can be further assigned etc, with the user being totally unaware.
An example (from A.C. Marshall) is
do30i = 1.100
statements
30 continue
Instead of a DO loop, because of the misprints, we will end up with a new real variable, do30i.
In consequence, we will always disable the implicit declarations by placing the command
implicit none
as the rst line after any USE statements (i.e. before the declarations sequence). With this command in
place, the existence of variables that are not explicitly declared will lead to a copilation error.
1.4 Assignment
An expression of the form
Z = Z + 2.0
fetches the value of Z from memory, adds 2.0, and stores the result at the same memory location Z. In short,
Znew = Zold +2:0. Note that the assignment = has a totally di erent meaning than mathematical equality
(here, the mathematical relation Z = Z +2:0 is an equation without solution).
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 11
1.5 Intrinsic Numerical Operations
NUMERIC TYPE :: a,b
NUMERIC TYPE :: [a] hnumerical operatori b
Fortran, like any other language, de nes several operators that act on numerical type variables. The
addition, subtraction, multiplication, division and exponentiation operators are denoted
+ ; ;  ; = ; and 
respectively. Nothe that addition and subtraction can be monadic (e.g. +2:1 or 2:1) or dyadic (e.g.
2:1 3:4) operators. Also note that we can raise a positive real number to a real power, e.g. 2:33:14, but
not ( 2:3)3:14.
In arithmetic expressions di erent numerical types can be used (will see later), but we usually cannot
mix numerical and character, or numerical and logical variables.
1.6 Literal Constants
We can use value constants directly in the statements; such values are called literal constants.
For example, a number can be raised to an integer power
Y = X4 ; Z = X( 6)
Both exponent values 4, 6 are written directly in the source text.
For real constants, we need to use either decimal point notation or scienti c notation (similar to oating
point notation base 10: we have a mantissa, followed by an exponent of 10; the expenent is preceded by E)
Y = X + 21.54 or Y = X + 2.154E+1
For double precision constants, we always use scienti c notation, but now the exponent marker E is replaced
by D, from double:
Y = X + 21.54D0 or Y = X + 2.154D+1
For complex literal constants we need to specify a (real part, imaginary part) pair. To assign the number
Z = 2:25+4:1i we do
Z = ( 2.25, 4.1 )
Logical constants can take one of two values, written as
Q = .TRUE. or Q = .FALSE.
Finally, character literal constants are delimited by single or double quotes
C = 'A' or C = A
If the delimiter is part of the string, the convention is to write it twice inside the string, for example
C = 'OMalley'
12 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
1.7 Relational Operators
numerical type :: a,b
logical :: a  relational operator  b
F77/F90 F90 Meaning
.GT.  greater than
.GE. = g.t. or equal to
.LE. = l.t. or equal to
.LT.  less than
.NE. = = not equal to
.EQ. == equal to
Relational operators compare the values of two numerical operands and deliver a logical result (.TRUE.
or .FALSE.). Note that for complex operands only .EQ. and .NE. can be used.
Example.
a = 12.0 if ( a.GE.10.0 ) then ...
The expression a .GE. 10 evaluates to .TRUE.
1.8 Intrinsic Logical Operations
logical :: a,b
logical :: [a]  logical operator  b
F90 Meaning
.NOT. monadic logical negation
.AND. logical AND (T.AND.T=T, else F)
.OR. logical OR (F.OR.F=F, else T)
.EQV. true, if both operands have same value
.NEQV. true, if operands have di erent values
Example.
real :: a, b
logical :: q1, q2
q1 = (.NOT.q2) .AND. (a.GT.b)g
1.9 Intrinsic Character Operations
1.9.1 Substrings
character(len=), parameter :: school=michigantech
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 13
Expression Value
school(2:4) ich
school(:8) michigan
school(9:) tech
school(4) error (string is scalar)
school(4:4) h (correct form)
1.9.2 Concatenation
character(len=), parameter :: 
state=michigan, name=tech
character(len=12) :: school
school = state // name
! produces michigantech
1.10 Operator Precedence
user-de ned monadic highest
 (tightest binding)
;= .
monadic +; .
dyadic +; .
== .
relational operators (.GT. etc.) .
.NOT. .
.AND. .
.OR. .
.EQV., .NEQV. (weakest binding)
user-de ned dyadic lowest
For multiple same-level operators evaluation is done left to right (except for ).
Paranthesis can alter the order of evaluation, and are recommended anyway for clarity. Sometimes
paranthesis can make subtle di erences, e.g.
A=B C 6= A=(B C)
or
A = 229;
B = 1:999999230;
C = 1:999998230;
X = A +B C ! X = 1; (over ow)
Y = A +(B C) ! Y = correct value
Homework 0.1 Add all possible paranthesis to indicate the order of evaluation for
:NOT:A:AND:B:EQV:C:OR:D:AND:E:OR:x:GT:y:AND:y:EQ:z
1.11 Intrinsic Functions
The most widely used functions are part of the Fortran system (are intrinsic to Fortran). This means that
the each Fortran system provides high quality implementations of these functions. We can call them without
14 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
linking to any mathematical library. Give some examples here.
1.12 Controlling the ow of the program
1.12.1 Conditional execution
IF Blocks permit conditional execution of a part of program.
Syntax:
[hnamei :] IF(hlogical expri ) THEN
hthen blocki
[
ELSEIF(hlogical expri ) THEN [hnamei]
helseif blocki
]
[
ELSE [hnamei]
helse blocki
]
END IF [hnamei]
Both ELSEIF and ELSE are optional. There can be any number of ELSEIF branches.
First the IF-s hlogical expriession is evaluated, and if .TRUE. the statements in the hthen blocki are
executed and control is then transferred to the rst statement following END IF. If .FALSE., the ELSEIF-
s hlogical expriessions are evaluated succesively, until the rst one is found to hold .TRUE. Then the
corresponding helseif blocki statements are executed.
If none of the ELSEIF-s hlogical expriessions is found .TRUE., the ELSE branch is taken (if present).
If the ELSE branch is not present the control is transferred to the rst instruction after END IF.
1.12.2 Examples
(Discuss control ow diagram with rombs and rectangles)
if (i .gt. 17) then
print*, i  17 !
end if
if (i .gt. 17) then
print*, i  17 !
else
print*, i = 17 !
end if
if (i .gt. 17) then
print*, i  17 !
elseif (i .eq. 17) then
print*, i = 17 !
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 15
elseif (i .eq. 16) then
print*, i = 16 !
else
print*, i  16 !
end if
Example of IF block use: solving a quadratic equation.
program quadratic eqn 1
implicit none
real::a,b,c ! coe of the quadratic eqn.
real::d ! determinant
real::x1,x2 ! solutions , if real (cases I, II)
real::xre,xim ! real and imaginary parts of solutions (case III)
!read in the coeÆcients
print, 'Please give quadr. eqn. coe . a, b, c:'
read,a,b,c
d=b2 4.0ac
! check the cases and treat them seperate
if (d.GT.0.0) then
x1=( b SQRT(d))/(2.0a)
x2=( b+SQRT(d))/(2.0a)
print,'The eqn. has two disctinct real roots: ', 
'x1=',x1,' x2=',x2
else if(d.EQ.0.0) then
x1= b/(2.0a)
print, 'The eqn. has two equal roots: ', 
'x1=x2=',x1
else ! d0
xre= b/(2.0a)
xim=SQRT( d)/(2.0a)
print, 'The eqn. has two complex conjugate roots: ',
xre,'+/ ',xim,'i'
end if
end program quadratic eqn 1
Example ofcomplex numbers use: solving a quadratic equation, Solution no. 2.
program quadratic eqn 2
implicit none
real::a,b,c
complex::d,x1,x2,sd
!read in the coeÆcients
print,'Please give a, b, c:'
read,a,b,c
!compute discriminant
d=b2 4ac
!sqrt(d): since d is complex, sqrt is complex
sd=SQRT(d)
! compute roots:
x1=( b+sd)/(2.0a)
x2=( b sd)/(2.0a)
print,'Roots are'
print,'X1=',x1
16 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
print,'X2=',x2
end program quadratic eqn 2
1.12.3 Repetitive action
DO Loops permit repetitive action.
Syntax:
DO hDO vari = hn expr1i;hn expr2i[;hn expr3i]
hexec stmtsi
END DO
The loop can be named and the body can contain EXIT or CYCLE statements.
The loop is worked out as follows
1. Evaluatenumericalexpressionshn expr1i, hn expr2iand, if present, hn expr3i. If notpresent, hn expr3i
is assumed to have the default value = 1.
2. Initialize the Do variable, DO var hn expr1i.
3. The iteration count is computed with the formula
#it = max

bhn expr2i hn expr1ihn expr3i
hn expr3i c;0

Note that both the number of iterations #it and the stride hexpr3i are evaluated before execution of
the loop begins. Subsequent value changes will have no in uence on the iteration process. If #it  0 the
execution cycle starts. At the end of each cycle, the iteration counter is decremented by 1
#it #it 1
and the DO variable (DO var) is modi ed by adding the stride
DO var DO var +hn expr3i
The iteration continues if #it  0, otherwise exits. As a consequence, at the end of the iterations, DO var
might assume a value di erent from hn expr2i.
Modifying the DO var inside the body loop is prohibited (and results in a compilation error).
For example, a missing stride hexpr3i is set by default to 1. The code
do i=1,9
print, i
end do
will execute the loop exactly 11 times, and will produce the output 1;2;3;:::9.
do i=1,9,2
print, i
end do
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 17
will produce the output 1;3;5;:::9.
A negative stride is possible, the code
do i=9,1, 2
print, i
end do
will produce the output 9;7;5:::1.
The loop
do i=9,1,1
print, i
end do
will produce no output since initially #it = 0. Also, the loop
do i=1,9, 1
print, i
end do nn
will produce no output since initially #it = max( 8;0) = 0.
EXIT statement nishes the innermost loop; however, with named do loops, it can exit the indicated
loop, regardless of its nesting level. Similarly, CYCLE outer cycles back to the outer loop, whereas a plain
CYCLE would have cycled back to the inner loop.
outer: do i=1,9
inner: do j=i,9
print*, before: ,i, j
if (j .gt. 3) cycle outer ! go to outer: do
print*, before: ,i, j
if (j .gt. 6) exit outer ! go to outer: do
print*, after: ,i,j
end do inner
end do outer
1.13 Application to DO loops: Fahrenheit to Celsius
Write a program that converts the temperature from Fahrenheit degrees to Celsius degrees (centigrades).
The steps are:
1. Problem formulation
2. Algorithm
3. Implementation
4. Run, and if the result is wrong, loop back.
program temp conv
implicit none
integer::n ! no. of temperatures to convert
18 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
real::f,c ! temp. values in F,C
integer::i ! loop counter
print,'No. of conversions='
read,n
do i=1,n
print,'Fahrenheit temp. no ',i,'='
read,f
c=9.0/5.0(f 32)
print,f,' F is ', c ,' C'
end do
end program temp conv
1.14 Problems
1. write a program that reads in the radius and computes the area of a circle;
2. extend the program to test whether the area is negative; if so just STOP. This introduces IF blocks,
and logical expressions;
3. extend the program to read 5 radii; this introduces a DO loop and integer variables; CYCLE and
EXIT.
4. extend the code to rst read all 5 radii and then compute all 5 areas; this introduces arrays. The
dimension (N=5) is a PARAMETER.
1.15 Input and Output
1.15.1 Standard (keyboard/console)
read, R
print, V
print, 'R = ', R or
print*, R = , R
1.15.2 File I/O
Opening les
In Fortran, les are designated by unit number, which is an integer number. Values from 0 to 6 are
reserved for standard I/O, standard error, etc. Usually user-de ned les have unit numbers of 10 and above.
Sometimes we need to read from/ write into user de ned les. In order for Fortran to be aware of the
existence of user-de ned les, we need to OPEN them (this is somehow similar to variable declaration).
For example, the statement
open( unit=10, file='data.txt', action='READ')
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 19
will open the le named 'data.txt'; the mode declaration states that this is an input (read-only) le; the
statement will allocate unit number 10 to the le 'data.txt'; from now on, all READ(10,*) will read in data
from this le.
The statement
open( unit=11, file='results.txt', action='WRITE')nendftabularg
will open the le named 'results.txt'; if not present, will create one; the mode declaration states that this
is an output (writeable) le; the statement will allocate unit number 11 to the le 'results.txt'; from now
on, all WRITE(11,*) will write data into this le. The list of arguments must be of standard intrinsic types
(unless explicit format is used). Each WRITE statement puts the arguments on a new line; non-advancing
WRITE is possible, but we need to use formats. Note that the statement, as is, will wipe out the content of
results.txt, should it previously exist.
It is possible to declare action='readwrite' for les which are both I/O.
Also not recommended, the two statements above can be abbreviated as
open( 10, 'data.txt', 'READ')
open( 11, 'results.txt ', ' WRITE')
The opened les may be closed with
close(10)
close(11)
The unit number can then be re-used (for a di erent le) in a subsequent OPEN statement.
Read and Write
The le read function has two parameters
read( unit=unit no, fmt=format label ) [ list of arguments ]
Each parameter can be replaced by a , with the meaning default unit or default format. We will talk
later about formats.
The call
read(5,) R, V
reads two reals from unit number 5 in default format. Unit 5 is prede ned, and is the standard input
(keyboard, unless redirected). Thus, an equivalent formulation is
read(,) R, V
The le write function is very similar,
write( unitn no, format label ) [ list of arguments ]
Each parameter can be replaced by a  (defaults). The call
write(6,) R, V
20 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
writes two reals onto unit number 6 in default format. Unit 6 is prede ned, and is the standard output
(monitor, unless redirected). Thus, an equivalent formulation is
write(,) R, V
The list of arguments must be of standard intrinsic types (unless explicit format is used). Each READ
statement reads the arguments from a new line; non-advancing READ is possible, but we need to use
formats.
1.15.3 Application
Modify the Fahrenheit to Celsius program to read the temperature (ÆF) from one le, and output it to
another le (ÆC).
program temp conv
implicit none
integer::i,n
real::f,c
integer::in=10,out=11 ! unit numbers
!open the les
open(unit=in,file='fahr.data',action='read')
open(unit=out,file='celsius.data',action='write')
!read and write how many temperatures
read(unit=in,fmt=) n
write(unit=out,fmt=) n
do i=1,n
read(unit=in,fmt=) f
c=9.0/5.0(f 32)
write(unit=out,fmt=) c
print,i,' F=',f,' is C=',c
end do
end program temp conv
The open, close, read and write functions can be checked if they performed ok using the IOSTAT param-
eter. In our case we check whether end-of- le was reached and if so we exit the loop. This way there is no
need to have the number of temperatures as the rst number in the le.
program temp conv 3
implicit none
real::f,c
integer::iostatus
!open the data le , F
open(unit=10,file='fahr2.data',action='read',iostat=iostatus)
!check if the le was opened properly
if(iostatus.NE.0) then
print,'Data file could not be opened'
stop ! terminates the program
end if
!open the result le
open(unit=11,file='celsius2.data',action='write',iostat=iostatus)
!check if the le opened properly
if(iostatus.NE.0) then
print,'Output file cannot be opened'
stop
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 21
end if
do
read(unit=10,fmt=,iostat=iostatus) f
!check if this is a valid read
if(iostatus.NE.0) then
print,'end of file reached'
exit
end if
c=5.0/9.0(f 32)
write(unit=11,fmt=) c
end do
end program temp conv 3
1.16 Arrays
Arrays are collection of elements of similar type. This data structure allows to implement mathematical
objects like vectors, matrices and tensors.
To declare an array with 3 real elements we use
real, dimension(3) :: v or
real :: v(3)
real v(3)
Particular entries of the array can be accessed with an index, running from 1 through the number of entries.
v(1)=1.0; v(2)=2.0; v(3)=3.0
One can assign values to all elements of v at once using an array constructor. A constructor is a list of scalar
values delimited by (/ ... /). For example the same initialization of v can be achieved using
v = (/ 1.0, 2.0, 3.0 /)
An even more compact initialization is achieved using an implicit do loop:
v = (/ (i , i=1,3) /)
In Fortran jargon the one-dimensional object v is called a rank-1 array (its entries are accessed using a
single index). One can de ne multi-dimensional arrays as well. A rank-2 array can be de ned for example
as
real, dimension(2,3) :: A or
real :: A(2,3)
real A(2,3))
A particular element is now accessed using two indices: A(i,j) where 1  i  2 and 1  j  3.
One can initialize a rank-n arrayusing constructors. The list of entriesin a constructoris one-dimensional;
we need to map this one-dimensional list onto the k-dimensional array. This is done using the intrinsic
function reshape. For example, we can initialize the 6 entries of A using
A = reshape ( (/ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 /), (/ 2, 3 /) )
22 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
The rst argument of the reshape function is the constructor, the second is another constructor containing
the shape of A. Reshape initializes the entries of A in column-wise order; the result of the above operation is
A =

1:0 3:0 5:0
2:0 4:0 6:0

:
Arrays can be used as arguments for input/output purposes. For example
read, A
will (expect to) read 6 numbers from the console and assign the values to elements of A in column-wise
order. Similarly,
print, A
prints the elements of A one after another in column-wise order.
1.16.1 Application
Vector times matrix multiplication.
program mvproduct
implicit none
real, dimension(3) :: V
real, dimension(2,3) :: A
real,dimension(2) :: W
integer :: i,j
print,'please give V(1:3)'
read,V
print,'Please give A (1:2,1:3)';
read,a
! The list of numbers from console is 1 dimensional, and is
! reshaped by the read function to the shape of A in column wise order.
! compute the matrixVector product
do i=1,2 ! for each entry of w, compute w(i)
w(i)=0.0
do j=1,3
w(i)=w(i)+a(i,j)V(j)
end do
end do
!print eVerything.
print,'A='
do i=1,2
print,(A(i,j),j=1,3) ! use implicit do loop to print all elements in row i
end do
print,'V=',V
print,'W=',w
!
end program mvproduct
Chapter 2
The Building Blocks of a Fortran
Application
2.1 Program Units
An F95 application will usually consist of several program units. One of them is the main program unit,
where the execution of the program starts, and where, usually, it ends if everything went all right with the
computation. The main program unit is delimited by the following keywords:
program hprogram namei
...
end program pname
The other four types of program units de ned in F95 are external functions, external subroutines, modules
and block data units. The beginnings and ends of these units are designated by the following syntaxes,
respectively:
function hfunction namei
...
end function hfunction namei
subroutine hsubroutine namei
...
end subroutine hsubroutine namei
module hmodule namei
...
end module hmodule namei
block data hblock data namei
...
end block data hblock data namei
23
24 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
As a general principle, the programming task is divided into smaller subtasks, which are then individually
solved. Di erent program units can implement di erent subtasks; programming units are standalone, in the
sense that they do not depend upon implementation details in the body of other program units; the units
communicate to each other via speci c interfaces, so one unit only needs to be aware of the interfaces to
other program units.
2.2 External Procedures
External procedures
 are parametrised blocks of code that perform a speci c task; this section of code is written once, and
can be re ered to as many times as needed;
 are independent units which may be compiled separately;
 communicate with other program units via arguments, returned values (functions only), and global
variables (to be discussed another lecture);
 can be used as arguments in other procedure calls.
Advantages
 avoid code duplication (when same task appears several times in our program);
 lead to modularization of programs. The general principle of dividing the problem into subproblems,
and managing the subproblems separately, can be naturally implemented using procedures;
 make software reusable (pieces can be used later in a di erent context);
In F95 there are 2 types of external procedures,
1. functions, and
2. subroutines.
2.3 External Functions
The syntax of a function declaration is
[htypei] FUNCTIONhfcn namei([hformal(dummy) argsi])
hdeclare formal(dummy) argsi
hdeclare local objectsi

hexecutable statementsi
END[FUNCTION[hfcn namei]]
For example, suppose we want to declare a function that receives the three coordinates of a cartesion
vector x,y,z and returns the euclidian norm of the vector, r =
p
x2 +y2 +z2 (this is also called the 2-norm).
The arguments x,y,z are REAL, and so is the returned value r.
The declaration could then be
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 25
! function that computes norm 2 real=type of the returned value
real function norm 2(x,y,z) !x,y,z are dummy arguments
implicit none !scope=body of the function
real::x,y,z !dummy args declaration
norm 2=SQRT(x2+y2+z2)
!function name behaves like a variable
!holding the return value
end function norm 2
!function for norm 1
real function norm 1(x,y,z)
implicit none
real::x,y,z
norm 1=abs(x)+abs(y)+abs(z)
end function norm 1
!function for norm in nity
real function norm inf(x,y,z)
implicit none
real::x,y,z
norm inf=max(abs(x),abs(y),abs(z))
end function norm inf
!the main program
program norms
implicit none
real::a,b,c
real,external::norm 1,norm 2,norm inf
print,'Please give coordinates a,b,c.'
read,a,b,c
print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args
print,'The 1 norm= ',norm 1(a,b,c)
print,'The inf norm= ',norm inf(a,b,c)
end program norms
Note that the function name hfcn namei (norm 2) behaves like a variable; when the function terminates,
this variable holds the result of the function (the return value of the function). The type of function is
the type of the returned result, i.e. the type of the result variable (norm2). This type is declared explicitly
as a pre x to the function name; in our example,
real function norm2(x,y,z).
Alternatively, this declaration can be mixed with the other declarations, for example
function norm2(x,y,z)
implicit none
real :: x, y, z, norm2
Either form is valid, and one declaration should always be given (otherwise the compiler will signal an error).
The variables x,y,z are called formal (dummy) arguments. They hold the input data for the function.
When the function is invoked, they will be replaced by actual values.
The calling program also declares the type of the function, padded with the EXTERNAL attribute. For
example, the calling program might read in the coordinates and print the 2-norm of the vector:
26 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
program print norm
implicit none
real, external :: norm2
real :: a, b, c
print, 'input~3~coordinates:'
read,a,b,c
print,'the norm is',norm2(a,b,c)
end program print norm
The declaration REAL, EXTERNAL :: norm2 tells the main program that norm2 is an external function
which returns a REAL result. Of course, the compiler can gure out itself that norm2 is a function by seeing
the name norm2 followed by paranthesis and the list of arguments at the place of call. Therefore, the
EXTERNAL attribute is not really necessary here, and we can simplify the declaration to REAL :: norm2.
However, it is good programming practice to have the EXTERNAL attribute, and I advise you to keep it
whenever external functions (or procedures) are used. In passing, we note that there are instances when
the name of the external function appears without the argument list - e.g. when the function name itself
is an argument in another function call. In these instances, the EXTERNAL attribute is mandatory, since the
compiler cannot distinguish between a function name and a variable name. Again, I advise you to give the
EXTERNAL attribute all the time: the code is more readable, and you do not have to remember the detailed
requirements for using this attribute.
The argument passing mechanism uses stacks. A stack is a memory structure which can be accessed (for
both writting (push) and reading (pop)) from the top only. An example of a stack is: [see picture].
2.4 Actual arguments, formal (dummy) arguments and local vari-
ables
The function is invoked by its name, followed by a list of actual arguments. When the call is issued, in
a special memory structure, called the program stack, 5 new locations are reserved; the addresses of the 3
arguments a,b,c are pushed, in this order, into the stack. The 4th
location contains the address of the real
variable norm2, which was declared in the main program and is expected to hold the result of the function
calculation. The 5th
location is dedicated to the local variable loc, about which we will talk later. The
control is then transferred from the caller (here, the main program) to the called function norm2. The
function sees the stack; from the function perspective, on the stack are (top to bottom): result variable
address, argument z address, argument y address, and argument x address. The formal (dummy) names
x,y,z are therefore just aliases for the actual variable names, to be used inside the function body (we say
that, when the funcion is called, formal (dummy) variables are replaced by actual variables). It is therefore
required that the order in which the actual arguments are supplied is precisely the order of formal (dummy)
arguments in the function declaration. Moreover, the type of nth
actual argument should coincide exactly
with the type its omologue (nth
) formal (dummy) argument.
The norm calculation is performed and the result stored in norm2 (the function knows the address of
this variable also!). At this point the control is returned to the main program. Here the function call
norm2(a,b,c) is simply replaced by the value found in the result variable norm2, and the computations in
the main program proceed further.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 27
?





7
H
H
H
H
H
H
H
H
H
H
H
H
H
H
H
Y
?
?
PROGRAM ...
END PROGRAM ...
FUNCTION 
END FUNCTION 
norm2(x,y,z)
norm2
norm2(a,b,c)
@z=@c
loc
@x=@a
@y=@b
@norm2
Stack
As presented here, the argument passing is said to be done by reference, since references to, rather
than values of arguments are put on the stack. Note that, in practice, the situation is more complicated; the
actual parameter-passing mechanism can be somewhat di erent than what we show here. This is the case,
for example, when the function is invoked with literal constant arguments (perfectly legal in F95)
print, norm2(1.0, 2.0, 3.0)
Nevertheless, the above discussion is useful to understand the inner logic of the F95 function declaration
and function call syntax.
The variable loc is called a local variable. Its scope is the body of the function. When the function is
called, space is allocated on the stack for loc; at this point the memory location does not carry any useful
information. When the control returns to the main program (the caller), the stack pointer is reset to its
previous value, wiping out all the information on stack; loc is therefore destroyed when the function is
exited. loc does not exist between function calls. Obviously, a new function call means a new incarnation
of loc, unrelated to the previous one; in particular, loc cannot remember its value from the previous call.
Note that IMPLICIT NONE should be used in any function declaration just as it is used in the main
program.
2.4.1 Implicit Interfaces
Implicit interfaces are the old, F77 way of communication. Separate procedures are desired to be as indepen-
dent as possible from one another (so that they can be written, compiled and maintained independently); in
particular, a procedure is totally ignorant of how a di erent procedure looks like.
Consider our norm example. The main program knows that norm2 is an external function that returns
a real value, but it has no information about the arguments.
Special problems arise when procedures call each other; the caller has very limited knowledge on the
28 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
called procedure; it passes a list of actual argument addresses to the called procedure; the called procedure
retrieves this addresses in order, and assumes they are the addresses of the formal (dummy) arguments.
The disadvantage of this approach is that the compiler is able to perform only limited consistency checks.
In F77, it is easy to make mistakes undetectable by the compiler when working with argument lists.
Consider, for example, the following subroutine
! function that computes norm 2 real=type of the returned value
real function norm 2(x,y,z) !x,y,z are dummy arguments
implicit none !scope=body of the function
real::x,y,z !dummy args declaration
norm 2=SQRT(x2+y2+z2)
!function name behaves like a variable
!holding the return value
end function norm 2
!function for norm 1
real function norm 1(x,y,z)
implicit none
real::x,y,z
norm 1=abs(x)+abs(y)+abs(z)
end function norm 1
!function for norm in nity
real function norm inf(x,y,z)
implicit none
real::x,y,z
norm inf=max(abs(x),abs(y),abs(z))
end function norm inf
!the main program
program norms
implicit none
real::a,b,c
real,external::norm 1,norm 2,norm inf
print,'Please give coordinates a,b,c.'
read,a,b,c
print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args
print,'The 1 norm= ',norm 1(a,b,c)
print,'The inf norm= ',norm inf(a,b,c)
end program norms
The accidental switch of arguments cannot be detected by the compiler and produces most curious results.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 29
2.5 Subroutines
An external subroutine a program unit that does all the communication with the rest of the world via
arguments (and global variables); it does not return a value. The syntax of a subroutine declaration is
SUBROUTINEhsbr namei([hformal(dummy) argsi])
hdeclare formal(dummy) argsi
hdeclare local objectsi

hexecutable statementsi
END[SUBROUTINE[hsbr namei]]
For example, suppose we want to declare a subroutine that receives the three coordinates of a cartesion
vector x,y,z and computes the 2-norm of the vector, r =
p
x2 +y2 +z2 (this is also called the 2-norm).
The arguments x,y,z are REAL, and so is the computed value r.
The declaration could then be
subroutine norm2s(x,y,z,r)
implicit none
real :: x,y,z,r
r = sqrt(x2+y2+z2)
end subroutine norm2s
The calling program invokes the subroutine using
call norm2s(a,b,c,d)
The CALL statement builds the argument stack and passes control to the subroutine; when END SUBROUTINE
is encountered, the control is returned to the calling program, at the rst statement after CALL. Unlike
functions, subroutines communicate with the calling program via arguments (or global variables) only - they
do NOT return a value associated with the subroutine's name.
For example, the main program might read in the coordinates and print the 2-norm of the vector:
program print norm
implicit none
external :: norm2s
real :: a, b, c, d
print*, input~3~coordinates:
read,a,b,c
call norm2s(a,b,c,d)
print*,the norm is,d
end program print norm
The declaration EXTERNAL :: norm2s tells the main program that norm2 is an external subroutine (we do
NOT have any type declaration associated with the name!). Again, in this particular context the declaration
is super uos, but, since it will be mandatory in other contexts, and since it improves readability, I strongly
recommend its use.
The actual arguments a,b,c,d replace the formal (dummy) arguments x,y,z,r (in this order) at the
time of call. The type and order of actual arguments should match exactly the type and order of their
omologue formal (dummy) arguments.
An IMPLICIT NONE statement should be given in each subroutine, just as it is given in the main program.
30 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
2.6 Comments
Procedures for most common programming tasks have already been written and are available for us to use
(many times for free!). One example is the set of intrinsic functions in F95. Another example are the
standard libraries for numerical computations. BLAS (Basic Linear Algebra Subroutines) is a collection of
modules that perform matrix and vector calculations. LAPACK is a complete set of subroutines for solving
numerical linear algebra problems.
Any time we have a programming task, and need to write a piece of code, it is advisable to check
whether a standard subroutine, in a standard collection, performs the same task for us. This cuts down
programming time; cuts down the likelihood of programming errors; usually, enhances performance; and, of
course, enhances software maintainability.
If we are to write our own procedures from scratch, here is some expert (and free!) advice, from A.C.
Marshall:
1. keep the procedures under 50 lines long, for a simple control structure;
2. make procedures as exible as possible, to allow for software reuse;
3. pass as many variables as possible as actual arguments, and rely as little as possible on global storage
or host association;
4. give procedures meaningful names, and plenty of comments;
5. there is absolutely no point in reinventing the wheel - use standard libraries whenever they o er
subroutines which solve the required task.
2.7 Modules
Modules are special program units, delimited by the following syntax:
module hmodule namei
...
end module hmodule namei
A module contains only declarations of di erent entities; it can contain no executable statements. Other
program units (functions, subroutines, main program or even other modules) can attach the module, and by
doing so they can see (have access to) the entities declared in the module.
Therefore, the functionality of a module is to declare objects and to make them available to other program
units. In this regard, they are di erent from procedures (which are supposed to perform some computations,
some I/O, etc).
We can attach a module to a program unit by inserting
use hmodule namei
as the rst statement in the program unit (right after the header, and right before any declaration).
Jargon: when a program unit USEs a module, it has access to the (public) objects declared in the module;
we say that the module entities are visible within that program unit by use-association.
Note that, in particular, modules can be attached to other modules, which in their turn can be attached
to other modules etc. In this situation we have to be careful not to create a circular de nition, which is of
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 31
course prohibited. An example of a circular, hence mistaken de nition, is: module 2 uses module 1, module
3 use module 2 and module 1 uses module 3.
What we said here is not the whole story with modules: it suÆces for now, but we will study more in
the future.
2.8 Scope of Variables
The scope of an entity is the part of the program where the entity is visible. The main program, a function
or a procedure are scoping units; an entity declared inside a scoping unit is visible throughout the unit.
In particular, a variable declared in the main program or in a procedure has the body of the pro-
gram/pocedure as its scope.
A variable is local (has local scope) if its scope is that of a scoping unit.
A variable whose scope is the entire program has global scope.
Some variables can be seen by multiple program units - by extension we will also talk about global
scope. Global storage (global scope variables) can be implemented using modules or common blocks. This
is discussed later in this chapter.
2.9 Lifetime of Variables
A variable is alive when its name is associated with a memory location. A variable is alive during the
execution of the program unit that declared it:
 variables declared in the main program live throughout the execution of our application;
 local variables (declared inside a function or subroutine and which are not formal (dummy) arguments
or global variables) are automatically allocated each time the procedure is called (allocation on function
stack) and automatically deallocated when the procedure returns. They are called automatic variables.
Their value is destroyed when the procedure returns; each call means a new variable is created.
SAVE attribute makes the variable static. It is allocated in a static part of the memory and is never
deallocated (during the execution of our program). In particular static variables preserve their value between
calls. Here is an example of a subroutine which counts how many times it has been called. The variable
icount is static due to the initialization.
! function that computes norm 2 real=type of the returned value
real function norm 2(x,y,z) !x,y,z are dummy arguments
implicit none !scope=body of the function
real::x,y,z !dummy args declaration
norm 2=SQRT(x2+y2+z2)
!function name behaves like a variable
!holding the return value
end function norm 2
!function for norm 1
real function norm 1(x,y,z)
implicit none
32 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
real::x,y,z
norm 1=abs(x)+abs(y)+abs(z)
end function norm 1
!function for norm in nity
real function norm inf(x,y,z)
implicit none
real::x,y,z
norm inf=max(abs(x),abs(y),abs(z))
end function norm inf
!the main program
program norms
implicit none
real::a,b,c
real,external::norm 1,norm 2,norm inf
print,'Please give coordinates a,b,c.'
read,a,b,c
print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args
print,'The 1 norm= ',norm 1(a,b,c)
print,'The inf norm= ',norm inf(a,b,c)
end program norms
Instead of initializing it, one can make the variable ilocal static using
integer, save :: ilocal
save ilocal
A single SAVE statement not followed by a list of variables has the e ect of declaring static(saving) all
local entities in a program unit that can be saved (note that formal (dummy) arguments and automatic
arrays cannot be saved).
2.10 Global Storage
We have seen so far that procedures communicate with the outside world via arguments and via returned
values (functions); all other variables declared are local, their scope is the body of the procedure only.
This fact has the advantage that procedures can be written without any knowledge of the program unit
from which they will be called - all that is required is that the interface is known.
However, for large programs, this will lead to very long argument lists, which can be a serious drawback
when programming (how about writing a routine with 10,000 arguments, and then calling it from 1,000
diferent places with di erent actual arguments?). It is therefore necessary to have a mechanism for global
storage, that is, to have variables that are visible from di erent program units, without being included in
the argument lists.
In F95, modules provide this extra mechanism of communication. Variables declared in a module are
visible within all procedures and programs which USE that particular module.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 33
2.10.1 Circle Example
We want to write two functions, which calculate the perimeter and the area of a circle, respectively. Both
functions need the value of . We de ne this value in a module:
module de ne pi
implicit none
real, parameter :: pi = 3.1415926
end module de ne pi
By USE-ing the module in both functions, we make sure that they see the same value of . The main
program reads in the value of the radius and prints the perimeter and the area of the circle.
real function perimeter(r)
use de ne pi
implicit none
real :: r
perimeter = 2.0pir
end function perimeter
real function area(r)
use de ne pi
implicit none
real :: r
area = pirr
end function area
program circle
implicit none
real :: r
real, external :: perimeter, area
print, 'radius ='
read, r
print,'area = ',area(r)
print,'perimeter = ',perimeter(r)
end program circle
2.10.2 Taylor Approximation of the Exponential
Consider a program which compares the Taylor approximation of the exponential with the intrinsic function.
We de ne a module Coeff which declares the order n of the approximation; the maximal order allowed
n max=10 and a vector b of coeÆcients for the Taylor polynomial. Note that, in the de nition, we include
speci cally the range to be 0:n max; this means that b will contain n max+1 elements, indexed from 0 to
n max.
module coe
integer :: n
integer, parameter :: n max = 10
real, dimension(0:n max) :: b
end module coe
program approx
use coe
implicit none
real :: x
integer :: i
external taylor exp
real, external :: eval
!
print*, please input order (n = 10)
read, n
n = min(n, n max)
call taylor exp
!
do i= 3,3
x= 2.0i
print, x,) exp=,exp(x),
34 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
; taylor=, eval(x)
end do
end program approx
subroutine taylor exp
! calculate the rst n coeÆcients
! in the taylor approx. of exp
use coe
implicit none
integer :: i
b(0) = 1.0
do i=1,n
b(i) = b(i 1)/real(i)
end do
end subroutine taylor exp
real function eval(x)
! evaluate the order n
! polyn. with coeÆcients b(i)
use coe
implicit none
real, intent(in) :: x
integer :: i
eval = b(n)
do i = n 1,0, 1
eval = b(i)+xeval
end do
end function eval
The subroutine Taylor exp USEs the module Coeff. As a consequence, it has access to all three global
variables n, n max and b. Note that this subroutine has no arguments, which is legal in F90, but does all the
communication with the ouside world via the global variables in the module Coeff. Taylor exp calculates
the rst n+1 coeÆcients in the Taylor series for the exponential function, and stores them in b(0) through
b(n).
The function Eval has just one input argument, x. It also USEs the module Coeff, hence it seesn,
n max and b. The function evaluates the value of the polynomial
b(0)+b(1) x +::: +b(n) xn ;
and returns this value to the calling program. It is easy to notice that a nested form evaluation algorithm
is used.
The main programalsoUSEsEval. Because of this, the variables in Eval exist aslong as the programruns;
they are e ectively static variables (we will discussed in the future about this). The subroutine Taylor exp,
the function Eval and the main program all have access to n, n max and b; any of them can read and write
any of these variables; in this sense, n, n max and b are called global variables. We say that the scope of n,
n max and b includes the main program, the subroutine and the function.
The main program reads in the desired order of approximation n; then, sets it to n max if it is larger than
this maximal value. When called, the subroutine Taylor exp lls in b(0) ... b(n) with the coeÆcients
of the nth Taylor polynomial. Finally, Eval is called several times, with di erent arguments, and the results
of the intrinsic function and this approximation are printed together, for comparison. Note that, once the
coeÆcients b(0) ... b(n) have been calculated and stored, they can be subsequently used to obtain any
number of approximate values Eval(x).
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 35
Homework 0.2 Write a module and two subroutines PUSH and POP to simulate a stack; the module will
allocate an 0:N MAX array, the memory space for the stack, and will contain a stack pointer (an integer to
keep track of the current position in the stack).
2.11 F77 Global Storage. Storage Association.
The default global storage facility in F77 are the COMMON blocks. It is likely that we will encounter them in
older software; however, we encourage the use of modules, not COMMON blocks, whenever global storage is
required.
The above version of our example program can be reformulated with COMMON blocks as follows:
program approx
integer :: n
real, dimension(0:10) :: b
common /coe / n, b
print*, please input order (n = 10)
read, n
n = min(n, 10)
call taylor exp
!
do i= 3,3
x= 2.0i
print, x,) exp=,exp(x), 
; taylor=, eval(x)
end do
end program approx
subroutine taylor exp
! calculate the rst
! n coeÆcients in
! the taylor approx. of exp
integer :: n
real, dimension(0:10) :: b
common /coe / n, b
!
integer :: i
b(0) = 1.0
do i=1,n
b(i) = b(i 1)/real(i)
end do
end subroutine taylor exp
real function eval(x)
! evaluate the order n
! polyn. with coeÆcients b(i)
integer :: n
real, dimension(0:10) :: b
common /coe / n, b
!
real, intent(in) :: x
integer :: i
36 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
eval = b(n)
do i = n 1,0, 1
eval = b(i)+xeval
end do
end function eval
A common block declaration consists by the keyword COMMON, followed by the common block's name
hcb namei (included between slashes); common blocks are recognized by their names within all program
units, i.e. COMMON block names are, by default, global names (they have to di er from any program unit
name). In the declaration, the name is followed by the list of variables stored in the COMMON block.
COMMON=hcb namei= var1;var2;var3;:::
All program units that invoke the
common /coe / ...
statement, for example, will have access to the common block /coeff/'s variables. Since we can have
variables shared by multiple units, common blocks are a mean of implementing global storage. Note that
an argument of a function or subroutine cannot be simultaneously a common block variable in the same
procedure.
Physically, a common block is a contiguous zone of memory (a block of memory) in which succesive
chunks of bytes are allocated to succesive variables (i.e. to the variables speci ed in the de nition of the
COMMON block). Speci cally, INTEGERs, REALs and LOGICALs are allocated 1 storage unit in the block,
DOUBLE PRECISION and COMPLEX variables are given 2 storage units (1 unit is usually 4 bytes, but depends
on the implementation). Characters are considered to have a di erent storage unit, incompatible with the
numerical storage unit; they are therefore incompatible with the numerical types; chracter and numerical
variables cannot be part of the same COMMON block.
The memory block can be seen by any program unit which includes its declaration, being therefore
COMMON to several program units.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 37
BB
B
B
BBB








L
L
LL
L
LLL
n
b(0)
COEFF
This storage scheme is also the main weakness of COMMON blocks. The reason is that the names of
variables var1;var2 ::: are local to the program unit which declares them, while the COMMON block name is
global. Thus, di erent program units can access the same common block, but can refer to the common block
variables with di erent (local) names. Of course, what counts is the relative position of a variable within
the block - the name is just a (local) alias for this position. Therefore, the types and the order of common
block variables have to be the same, but their names can di er (pretty much like the list of formal (dummy)
vs. the list of actual arguments).
For example, consider the following subroutine which prints the rst two elements of the COMMON block
COEFF.
subroutine p2
integer :: n, p
common /coe / n, p
print, n, p
end subroutine p2
The compiler cannot check that types of the succesive variables in COMMON blocks match for di erent
common block de nitions; it will just check that local de nitions are consistent. Now, our intent was to
have rst an integer (n), then a real number b(0); by mistake, we declared both integers, and the compiler
cannot help us; in consequence, the 32 bits of the real number b(0) will be interpreted as the 32 bits of a
signed integer (in two's complement) p; instead of 1.0 we obtain 1065353216.
In addition, common blocks containing data of heterogeneous(di erent) types may lead to memory
missalignments.
38 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
2.12 BLOCK DATA statements
To initialize the variables in a COMMON BLOCK we can use the BLOCK DATA construct. For example,
block data coe init
integer :: n
real, dimension(0:10) :: b
common /coe / n, b
data n /10/
data b /1.0000000000e+00, 1.0000000000e+00, 0.5000000000e+00, 
0.1666666667e+00, 4.1666666667e 02, 8.3333333333e 03, 
1.3888888889e 03, 1.9841269841e 04, 2.4801587302e 05, 
2.7557319224e 06, 2.7557319224e 07/
end block data coe init
initializes the elements of the (coeff) COMMON block variables to n=1, x(1) = 3.0, x(2) = 5.0. Note
that a BLOCK DATA construct includes the COMMON block statement, and the de nitions of the COMMON block
variables; also, it contains the DATA statements, which initialize the variables with the prescribed values
(i.e. at compile time the allocated memory slots for the speci ed variables are written with the given initial
values).
The statement
save /coe /
makes the common block static storage; it will be kept in memory for the whole duration of the current
execution (in practice most Fortran systems will automatically make all common blocks static, but we should
not rely on this!).
2.13 Include les
To avoid the problems of inconsistent common block declarations it is common practice to place the common
blocks and their variable declarations in a le, and then to include the le in di erent program units which
use the common block. For example, the le coe .cmm may contain
integer :: n
real, dimension(0:10) :: b
common /coe / n, b
and we may use
include 'coe .cmm'
This is equivalent to inserting (rewritting) the content of coe .cmm at each place where the le is included.
We therefore avoid repeating the same declarations and are sure of the consistency.
2.14 More on Storage Association
Fortran allows for a special, unnamed common block, called the blank COMMON block. It is declared as
common // var 1, var 2, ..., var n
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 39
Blank common block is useful when most, or a large number of routines, need to share same variables. Some
special features of the blank common block are
 contained data is automatically static,and
 it cannot be initialized in a BLOCK DATA statement;
 the compiler is more permissive (e.g. it allows the blank common block to be invoked with a di erent
number of variables in di erent program units).
In F77 several entities (scalar or array) can be associated with the same memory location, using
equivalence ( var 1, var 2 , ..., var n )
All the variables in the list are stored in the same memory locations, more exactly, their storage spaces start
at the same address in the memory.
EQUIVALENCE is usually used in conjunction with large common blocks, to identify the parts of the block
for the current procedure. For example, a common block /VERY LONG/ can store 28 real arrays, containing
a total of 15,421 real elements
common /very long/ a(7311), b(121), ..., z(1272)
Suppose in a procedure only the second array, B(121) is used; we can use the declaration
real b(121)
common /very long/ blk(15421)
equivalence (b, blk(7312))
(we employed F77 syntax on purpose).
Sometimes the results of EQUIVALENCE statements are hard to understand. For example
real x, y(2), z
complex c
equivalence (x,y,c), (y(2), z)
c = cmplx(1.0,2.0)
has the e ect of setting y(1)  x  REAL(c) = 1.0 and y(2)  z  AIMAG(c) = 2.0.
40 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
Chapter 3
More on Flow Control
3.1 Named IF and DO Blocks
Naming IF blocks is mainly cosmetic, but is useful to improve readability when nested IF blocks are used
(nesting can go to any depth!). For example
lev0: if (a.gt.b) then
print*, a is larger
elseif (a.lt.b) then lev0
lev1: if (b.gt.c) then
print*, b is larger
elseif (b.lt.c) then lev1
lev2: if (c.gt.d) then
print*, c is larger
end if lev2
end if lev1
end if lev0
A similar discussion for DO loops.
3.2 The IF Statement
Is a shorter form of an IF block, when neither the ELSEIFs nor the ELSE branches are present. Syntax:
if (hlogical expressioni) statement
If the hlogical expriession is .TRUE. then the (single) hstatementi is executed; if .FALSE., then control
is just passed further. Note that the single hstatementi is usually a very powerfull instruction, like EXIT or
GOTO.
Homework 0.3 Write a program that reads 3 lengths (3 real numbers) and reports back if they can de ne
a triangle; if yes, print a message if the de ned triangle is equilateral, isosoles, or arbitrary.
41
42 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
3.3 More on DO Loops
The general syntax of a do loop is:
[hnamei :]do
hexec stmtsi
end do [hnamei :]
The body of the loop (hexec stmtsi) is delimited by DO and ENDDO keywords. A name can be associated
with the DO loop. hexec stmtsi are executed as many times as required. As it stands the loop will cycle
inde nitely; we have to append the loop with the proper mechanism to control the number of iterations.
3.3.1 Conditional EXIT
do
hexec stmts1i
if ( hlogical expri) exit
hexec stmts2i
end do
The hlogical expriession is evaluated at every sweep through the loop. If true, EXIT is executed, which (of
course!) exits the loop and transfers control to the rst statement after END DO. Usually, EXIT is in either
the rst or the last statement in the body of the loop, for improved readability. An EXIT statement outside
the body of a loop is an error.
Conditional EXIT loops are useful when we want the input data to control the number of iterations.
For example, the Fahrenheit to Celsius program can read and convert temperatures until an unrealistic
temperature, say 1000 or less, is read in. Try this example!
3.3.2 Conditional CYCLE
do
hexec stmts1i
if ( hlogical expri) cycle
hexec stmts2i
end do
If hlogical expriession is true, CYCLE is executed; it forcess control to bypass hexec stmts2i and to jump
to the DO statement; the loop will then start the next iteration. A CYCLE statement outside the body of a
loop is an error.
For example, the Fahrenheit to Celsius program can skip the conversion of the temperatures that are
unreasonably high, say 1000 or above. Try this example!
3.3.3 Exit and Cycle with named loops
EXIT statement nishes the innermost loop; however, with named do loops, it can exit the indicated loop,
regardless of its nesting level. Similarly, CYCLE outer cycles back to the outer loop, whereas a plain CYCLE
would have cycled back to the inner loop.
outer: do i=1,9
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 43
inner: do j=i,9
print*, before: ,i, j
if (j  3) cycle outer ! go to outer: do
print*, before: ,i, j
if (j  6) exit outer ! go to outer: do
print*, after: ,i,j
end do inner
end do outer
3.3.4 Initial Test (DO...WHILE) Loop
Syntax:
do while hlogical expri
hexec stmtsi
end do
The hlogical expriession is evaluated at the beginning of every iteration; the loop executes only if it holds
.TRUE. Clearly, the operands of the hlogical expriession need to be modi ed during execution (otherwise
the loop will either not execute or continue forever). Initial test loops are standard in most programming
languages and have numerous applications.
The DO...WHILE LOOP can be replaced with the functionally equivalent construction: DO; IFEXIT
... END DO.
3.4 SELECT CASE
Syntax:
[hnamei :] SELECT CASE (hcase expri )
[
CASE (hcase selectori) [hnamei]
hexec stmtsi
]
[
CASE DEFAULT [hnamei]
hexec stmtsi
]
END SELECT [hnamei]
 hcase expri must be a scalar of type INTEGER, LOGICAL or CHARACTER;
 hcase selectori can be a single value (.TRUE.) or a range (12 : 16); one cannot use an expression as
case selector.
 hcase expri is evaluated and compared to the hcase selectoris, in order; when a match is found, the
branch is taken and the corresponding hexec stmtsi executed. If no hcase selectori matches then the
CASE DEFAULT branch is executed, if present.
 At the end of hexec stmtsi in the selected branch the control is passed to the rst statement following
END SELECT.
44 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
A CASE SELECT function can be implemented with an IF ... ELSEIF... ENDIF construction; how-
ever, the former needs a di erent expression to evaluate at each branch, and is therefore less eÆcient.
Example:
select case (i)
case (:0) ; print*, i=0
case (1) ; print*, i=1
case default; print*, i=2
end select
program season
implicit none
integer::month
print,'Give month'
read,month
select case (month)
case (12,1,2)
print,'Month ',month,' is in winter'
case(3:5) ! this is range from 3 to 5
print,'Month ',month,' is in spring'
case(6:8)
print,'Month ',month,' is in summer'
case(9:11)
print,'Month ',month,' is in fall '
case default
print,'invalid month: ',month
end select
end program season
3.5 Exceptional Situations
All the control ow constructs described so far enter the construct at only one place (IF, DO or SELECT CASE)
and exit the construct at only one place also (END IF, END DO or END SELECT respectively). This enables
the programmer to easily control the logic of the code.
In some situations, it is convenient to have the possibility to exit the constructs at di erent places; for
example, if an error in the data was detected, measures have to be taken right away, even if we are in the
middle of several multiple nested DO loops.
Fortran provides 3 di erent means to achieve this.
3.5.1 STOP
The statement STOP immediately terminates the execution of the program. It is used when the program has
detected an unrecoverable error.
3.5.2 RETURN
RETURN is called from a subroutine, causing its execution to be terminated immediately and transferring the
control back to the caller.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 45
3.5.3 GO TO
Syntax:
GOTO hstmt labeli or GO TO hstmt labeli
A statement label (hstmt labeli) is a number of up to 5 digits (1:::99999), written in column 1 through
5 (this is inherited from the xed form). It is separated from the statement it labels by at least 1 blank.
For example,
12345 PRINT*, Error
001 CONTINUE
The statement GOTOhstmt labeli immediately transfers control to the statement labeled by hstmt labeli.
IF (A .EQ. 0) GO TO 12345
........
12345 PRINT*, Error: A=0
! Begin the recover-from-error strategy
The hstmt labeli can be an integer expression, evaluated at run time.
Except when needed to recover from error situations, we will avoid the use of GO TO, since it leads to
unstructured programs.
Experience over many years has shown [GOTO statements] to be the single biggest cause of bad pro-
gramming habits and consequent programming errors. (T. Ellis, I. Philips, T. Lahey).
46 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
Chapter 4
Computer Representation of Numbers
and Computer Arithmetic
4.1 Binary numbers
In the decimal system, the number 107.625 means
107:625 = 1102
+7100
+610 1
+210 2
+510 3
:
Such a number is the sum of terms of the form fa digit times a di erent power of 10g - we say that 10 is the
basis of the decimal system. There are 10 digits (0,...,9).
All computers today use the binary system. This has obvious hardware advantages, since the only digits
in this system are 0 and 1. In the binary system the number is represented as the sum of terms of the form
fa digit times a di erent power of 2g. For example,
(107:625)10 = 26
+25
+23
+21
+20
+2 1
+2 3
= (1101011:101)2 :
Arithmetic operations in the binary system are performed similarly as in the decimal system; since there are
only 2 digits, 1+1=10.
1 1 1 1 0
+ 1 1 0 1
1 0 1 0 1 1
1 1 1
 1 1 0
0 0 0
1 1 1
1 1 1
1 0 1 0 1 0
Decimal to binary conversion. For the integer part, we divide by 2 repeatedly (using integer division);
the remainders are the successive digits of the number in base 2, from least to most signi cant.
Quotients 107 53 26 13 6 3 1 0
Remainders 1 1 0 1 0 1 1
For the fractional part, multiply the number by 2; take away the integer part, and multiply the fractional
part of the result by 2, and so on; the sequence of integer parts are the digits of the base 2 number, from
47
48 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
most to least signi cant.
Fractional 0:625 0:25 0:5 0
Integer 1 0 1
Octal representation. A binary number can be easily represented in base 8. Partition the number
into groups of 3 binary digits (23
= 8), from decimal point to the right and to the left (add zeros if needed).
Then, replace each group by its octal equivalent.
(107:625)10 = ( 1 101 011 : 101 )2 = (153:5)8
Hexadecimal representation. To represent a binary number in base 16 proceed as above, but now
partition the number into groups of 4 binary digits (24
= 16). The base 16 digits are 0,...,9,A=10,...,F=15.
(107:625)10 = ( 0110 1011 : 1010 )2 = (6B:A)16
1. Convert the following binary numbers to decimal, octal and hexa: 1001101101.0011, 11011.111001;
2. Convert the following hexa numbers to both decimal and binary: 1AD.CF, D4E5.35A;
3. Convert the following decimal numbers to both binary and hexa: 6752.8756, 4687.4231.
4.2 Memory
The data and the programs are stored in binary format in computer's memory. Memory is organized in
bytes, where 1 byte = 8 binary digits. In practice we use multiples of byte.
1 Kb 1024 bytes 210
bytes
1 Mb 1024 Kb 220
bytes
1 Gb 1024 Mb 230
bytes
There are several physical memories in a computer; they form a memory hierarchy. Note that the physical
chips for cache memory use a di erent technology than the chips for main memory; they are faster, but
smaller and more expensive. Also, the disk is a magnetic storage media, a di erent technology than the
electronic main memory; the disk is larger, cheaper but slower.
Memory Type Size Access time
Registers 8 bytes 1 clock cycle
Cache, Level 1 126 Kb - 512 Kb 1 ns
Cache, Level 2 512 Kb - 8 Mb 10 ns
Main memory 8 Mb - 2 Gb 60 ns
Hard drive 2 Gb - 40 Gb 10 ms
4.2.1 Characters in Memory
Characters are letters of the alphabet, both upper and lower case, punctuation marks, and various other
symbols. In the ASCII convention (American Standard Code for Information Interchange) one character
uses 7 bits. (there are at most 27
= 128 di erent characters representable with this convention). As a
consequence, each character will be stored in exactly one byte of memory.
c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 49
Homework 0.4 Implement the following program
program test char
character a, b
a='s'
write(6,) 'Please input b:'
READ, b
write(6,) a,b
stop
end
Note how characters are declared and initialized. Run the program successfully.
4.2.2 The Memory Model
When programming, we think of the main memory as a long sequence of bytes. Bytes are numbered
sequentially; each byte is designated by its number, called the address.
For example, suppose we have a main memory of 4 Gb; there are 232
bytes in the memory; addresses
ranging from 0:::232
1 can be represented using 32 bits (binary digits), or (equiv.) by 8 hexa digits.
Suppose we want to store the string john. With one character per byte, we need 4 successive memory
locations (bytes) for the string. Each memory location has an address and a content.
'j'
'o'
'h'
'n'
Content
1B56AF75
1B56AF74
1B56AF73
1B56AF72
Address
When we declare a variable, the corresponding number of bytes is reserved in the memory; the name of the
variable is just an alias for the address of the rst byte in the storage.
4.3 Reprentation of Signed Integers
m binary digits (bits) of memory can store 2m di erent numbers. They can be positive integers between
00...00 = (0)10 and 11...11 = (2m 1)10. For example, using m = 3 bits, we can represent any integer
between 0 and 7.
If we want to represent signed integers (i.e. both positive and negative numbers) using m bits, we can
use one of the following methods:
50 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
 Sign/Magnitude representation. Reserve the rst bit for the signum (for example, let 0 denote positive
numbers, and 1 negative numbers); the other m 1 bits will store the magnitude (the absolute value)
of the number. In this case the range of numbers represented is 2m 1
+1 to +2m 1
1. With m = 3
there are 2 bits for the magnitude, di erent possible magnitudes, between 0 and 127; each of these
can have a positive and negative sign. Note that with this representation we have both positive and
negative zero. If we make the convention that the sign bit is 1 for negative numbers we have
Number10 ([S]M)2
-3 [1]11
-2 [1]10
-1 [1]01
-0 [1]00
+0 [0]00
+1 [0]01
+2 [0]10
+3 [0]11
 Two's complement representation. All numbers from 2m 1
to +2m 1
1 are represented by the
smallest positive integer with which they are congruent modulo 2m. With m = 3, for example, we have
Number10 (2C)10 (2C)2
-4 4 100
-3 5 101
-2 6 110
-1 7 111
0 0 000
1 1 001
2 2 010
3 3 011
Note that the rst bit is 1 for negative numbers, and 0 for nonnegative numbers.
 Biased representation. A number x 2 [ 2m 1
;2m 1
1] is represented by the positive value 
x =
x +2m 1
2 [0;2m 1]. Adding the bias 2m 1
gives positive results.
Number10 (biased)10 (biased)2
-4 0 000
-3 1 001
-2 2 010
-1 3 011
0 4 100
1 5 101
2 6 110
3 7 111
The rst bit is 0 for negative numbers, and 1 for nonnegative numbers.
4.3.1 Integers in Memory
Onebyteof memorycanstore28
= 256di erent numbers. Theycanbe positiveintegersbetween 00000000 =
(0)10 and 11111111 = (255)10.
Other documents randomly have
different content
are approached in which there is no movement at all, knowledge
becomes really demonstrative, certain, perfect—truth pure and
unalloyed. The heavens can be more truly known than the earth,
God the unmoved mover than the heavens.
From this fact follows the superiority of contemplative to practical
knowledge, of pure theoretical speculation to experimentation, and
to any kind of knowing that depends upon changes in things or that
induces change in them. Pure knowing is pure beholding, viewing,
noting. It is complete in itself. It looks for nothing beyond itself; it
lacks nothing and hence has no aim or purpose. It is most
emphatically its own excuse for being. Indeed, pure contemplative
knowing is so much the most truly self-enclosed and self-sufficient
thing in the universe that it is the highest and indeed the only
attribute that can be ascribed to God, the Highest Being in the scale
of Being. Man himself is divine in the rare moments when he attains
to purely self-sufficient theoretical insight.
In contrast with such knowing, the so-called knowing of the artisan
is base. He has to bring about changes in things, in wood and stone,
and this fact is of itself evidence that his material is deficient in
Being. What condemns his knowledge even more is the fact that it is
not disinterestedly for its own sake. It has reference to results to be
attained, food, clothing, shelter, etc. It is concerned with things that
perish, the body and its needs. It thus has an ulterior aim, and one
which itself testifies to imperfection. For want, desire, affection of
every sort, indicate lack. Where there is need and desire—as in the
case of all practical knowledge and activity—there is incompleteness
and insufficiency. While civic or political and moral knowledge rank
higher than do the conceptions of the artisan, yet intrinsically
considered they are a low and untrue type. Moral and political action
is practical; that is, it implies needs and effort to satisfy them. It has
an end beyond itself. Moreover, the very fact of association shows
lack of self-sufficiency; it shows dependence upon others. Pure
knowing is alone solitary, and capable of being carried on in
complete, self-sufficing independence.
In short, the measure of the worth of knowledge according to
Aristotle, whose views are here summarized, is the degree in which
it is purely contemplative. The highest degree is attained in knowing
ultimate Ideal Being, pure Mind. This is Ideal, the Form of Forms,
because it has no lacks, no needs, and experiences no change or
variety. It has no desires because in it all desires are consummated.
Since it is perfect Being, it is perfect Mind and perfect Bliss;—the
acme of rationality and ideality. One point more and the argument is
completed. The kind of knowing that concerns itself with this
ultimate reality (which is also ultimate ideality) is philosophy.
Philosophy is therefore the last and highest term in pure
contemplation. Whatever may be said for any other kind of
knowledge, philosophy is self-enclosed. It has nothing to do beyond
itself; it has no aim or purpose or function—except to be philosophy
—that is, pure, self-sufficing beholding of ultimate reality. There is of
course such a thing as philosophic study which falls short of this
perfection. Where there is learning, there is change and becoming.
But the function of study and learning of philosophy is, as Plato put
it, to convert the eye of the soul from dwelling contentedly upon the
images of things, upon the inferior realities that are born and that
decay, and to lead it to the intuition of supernal and eternal Being.
Thus the mind of the knower is transformed. It becomes assimilated
to what it knows.
Through a variety of channels, especially Neo-Platonism and St.
Augustine, these ideas found their way into Christian theology; and
great scholastic thinkers taught that the end of man is to know True
Being, that knowledge is contemplative, that True Being is pure
Immaterial Mind, and to know it is Bliss and Salvation. While this
knowledge cannot be achieved in this stage of life nor without
supernatural aid, yet so far as it is accomplished it assimilates the
human mind to the divine essence and so constitutes salvation.
Through this taking over of the conception of knowledge as
Contemplative into the dominant religion of Europe, multitudes were
affected who were totally innocent of theoretical philosophy. There
was bequeathed to generations of thinkers as an unquestioned
axiom the idea that knowledge is intrinsically a mere beholding or
viewing of reality—the spectator conception of knowledge. So deeply
engrained was this idea that it prevailed for centuries after the actual
progress of science had demonstrated that knowledge is power to
transform the world, and centuries after the practice of effective
knowledge had adopted the method of experimentation.
Let us turn abruptly from this conception of the measure of true
knowledge and the nature of true philosophy to the existing practice
of knowledge. Nowadays if a man, say a physicist or chemist, wants
to know something, the last thing he does is merely to contemplate.
He does not look in however earnest and prolonged way upon the
object expecting that thereby he will detect its fixed and
characteristic form. He does not expect any amount of such aloof
scrutiny to reveal to him any secrets. He proceeds to do something,
to bring some energy to bear upon the substance to see how it
reacts; he places it under unusual conditions in order to induce some
change. While the astronomer cannot change the remote stars, even
he no longer merely gazes. If he cannot change the stars
themselves, he can at least by lens and prism change their light as it
reaches the earth; he can lay traps for discovering changes which
would otherwise escape notice. Instead of taking an antagonistic
attitude toward change and denying it to the stars because of their
divinity and perfection, he is on constant and alert watch to find
some change through which he can form an inference as to the
formation of stars and systems of stars.
Change in short is no longer looked upon as a fall from grace, as a
lapse from reality or a sign of imperfection of Being. Modern science
no longer tries to find some fixed form or essence behind each
process of change. Rather, the experimental method tries to break
down apparent fixities and to induce changes. The form that remains
unchanged to sense, the form of seed or tree, is regarded not as the
key to knowledge of the thing, but as a wall, an obstruction to be
broken down. Consequently the scientific man experiments with this
and that agency applied to this and that condition until something
begins to happen; until there is, as we say, something doing. He
assumes that there is change going on all the time, that there is
movement within each thing in seeming repose; and that since the
process is veiled from perception the way to know it is to bring the
thing into novel circumstances until change becomes evident. In
short, the thing which is to be accepted and paid heed to is not what
is originally given but that which emerges after the thing has been
set under a great variety of circumstances in order to see how it
behaves.
Now this marks a much more general change in the human attitude
than perhaps appears at first sight. It signifies nothing less than that
the world or any part of it as it presents itself at a given time is
accepted or acquiesced in only as material for change. It is accepted
precisely as the carpenter, say, accepts things as he finds them. If he
took them as things to be observed and noted for their own sake, he
never would be a carpenter. He would observe, describe, record the
structures, forms and changes which things exhibit to him, and leave
the matter there. If perchance some of the changes going on should
present him with a shelter, so much the better. But what makes the
carpenter a builder is the fact that he notes things not just as
objects in themselves, but with reference to what he wants to do to
them and with them; to the end he has in mind. Fitness to effect
certain special changes that he wishes to see accomplished is what
concerns him in the wood and stones and iron which he observes.
His attention is directed to the changes they undergo and the
changes they make other things undergo so that he may select that
combination of changes which will yield him his desired result. It is
only by these processes of active manipulation of things in order to
realize his purpose that he discovers what the properties of things
are. If he foregoes his own purpose and in the name of a meek and
humble subscription to things as they really are refuses to bend
things as they are to his own purpose, he not only never achieves
his purpose but he never learns what the things themselves are.
They are what they can do and what can be done with them,—
things that can be found by deliberate trying.
The outcome of this idea of the right way to know is a profound
modification in man's attitude toward the natural world. Under
differing social conditions, the older or classic conception sometimes
bred resignation and submission; sometimes contempt and desire to
escape; sometimes, notably in the case of the Greeks, a keen
esthetic curiosity which showed itself in acute noting of all the traits
of given objects. In fact, the whole conception of knowledge as
beholding and noting is fundamentally an idea connected with
esthetic enjoyment and appreciation where the environment is
beautiful and life is serene, and with esthetic repulsion and
depreciation where life is troubled, nature morose and hard. But in
the degree in which the active conception of knowledge prevails,
and the environment is regarded as something that has to be
changed in order to be truly known, men are imbued with courage,
with what may almost be termed an aggressive attitude toward
nature. The latter becomes plastic, something to be subjected to
human uses. The moral disposition toward change is deeply
modified. This loses its pathos, it ceases to be haunted with
melancholy through suggesting only decay and loss. Change
becomes significant of new possibilities and ends to be attained; it
becomes prophetic of a better future. Change is associated with
progress rather than with lapse and fall. Since changes are going on
anyway, the great thing is to learn enough about them so that we be
able to lay hold of them and turn them in the direction of our
desires. Conditions and events are neither to be fled from nor
passively acquiesced in; they are to be utilized and directed. They
are either obstacles to our ends or else means for their
accomplishment. In a profound sense knowing ceases to be
contemplative and becomes practical.
Unfortunately men, educated men, cultivated men in particular, are
still so dominated by the older conception of an aloof and self-
sufficing reason and knowledge that they refuse to perceive the
import of this doctrine. They think they are sustaining the cause of
impartial, thorough-going and disinterested reflection when they
maintain the traditional philosophy of intellectualism—that is, of
knowing as something self-sufficing and self-enclosed. But in truth,
historic intellectualism, the spectator view of knowledge, is a purely
compensatory doctrine which men of an intellectual turn have built
up to console themselves for the actual and social impotency of the
calling of thought to which they are devoted. Forbidden by
conditions and held back by lack of courage from making their
knowledge a factor in the determination of the course of events,
they have sought a refuge of complacency in the notion that
knowing is something too sublime to be contaminated by contact
with things of change and practice. They have transformed knowing
into a morally irresponsible estheticism. The true import of the
doctrine of the operative or practical character of knowing, of
intelligence, is objective. It means that the structures and objects
which science and philosophy set up in contrast to the things and
events of concrete daily experience do not constitute a realm apart
in which rational contemplation may rest satisfied; it means that
they represent the selected obstacles, material means and ideal
methods of giving direction to that change which is bound to occur
anyway.
This change of human disposition toward the world does not mean
that man ceases to have ideals, or ceases to be primarily a creature
of the imagination. But it does signify a radical change in the
character and function of the ideal realm which man shapes for
himself. In the classic philosophy, the ideal world is essentially a
haven in which man finds rest from the storms of life; it is an asylum
in which he takes refuge from the troubles of existence with the
calm assurance that it alone is supremely real. When the belief that
knowledge is active and operative takes hold of men, the ideal realm
is no longer something aloof and separate; it is rather that collection
of imagined possibilities that stimulates men to new efforts and
realizations. It still remains true that the troubles which men
undergo are the forces that lead them to project pictures of a better
state of things. But the picture of the better is shaped so that it may
become an instrumentality of action, while in the classic view the
Idea belongs ready-made in a noumenal world. Hence, it is only an
object of personal aspiration or consolation, while to the modern, an
idea is a suggestion of something to be done or of a way of doing.
An illustration will, perhaps, make the difference clear. Distance is an
obstacle, a source of trouble. It separates friends and prevents
intercourse. It isolates, and makes contact and mutual
understanding difficult. This state of affairs provokes discontent and
restlessness; it excites the imagination to construct pictures of a
state of things where human intercourse is not injuriously affected
by space. Now there are two ways out. One way is to pass from a
mere dream of some heavenly realm in which distance is abolished
and by some magic all friends are in perpetual transparent
communication, to pass, I say, from some idle castle-building to
philosophic reflection. Space, distance, it will then be argued, is
merely phenomenal; or, in a more modern version, subjective. It is
not, metaphysically speaking, real. Hence the obstruction and
trouble it gives is not after all real in the metaphysical sense of
reality. Pure minds, pure spirits, do not live in a space world; for
them distance is not. Their relationships in the true world are not in
any way affected by special considerations. Their
intercommunication is direct, fluent, unobstructed.
Does the illustration involve a caricature of ways of philosophizing
with which we are all familiar? But if it is not an absurd caricature,
does it not suggest that much of what philosophies have taught
about the ideal and noumenal or superiorly real world, is after all,
only casting a dream into an elaborate dialectic form through the
use of a speciously scientific terminology? Practically, the difficulty,
the trouble, remains. Practically, however it may be metaphysically,
space is still real:—it acts in a definite objectionable way. Again, man
dreams of some better state of things. From troublesome fact he
takes refuge in fantasy. But this time, the refuge does not remain a
permanent and remote asylum.
The idea becomes a standpoint from which to examine existing
occurrences and to see if there is not among them something which
gives a hint of how communication at a distance can be effected,
something to be utilized as a medium of speech at long range. The
suggestion or fancy though still ideal is treated as a possibility
capable of realization in the concrete natural world, not as a superior
reality apart from that world. As such, it becomes a platform from
which to scrutinize natural events. Observed from the point of view
of this possibility, things disclose properties hitherto undetected. In
the light of these ascertainments, the idea of some agency for
speech at a distance becomes less vague and floating: it takes on
positive form. This action and reaction goes on. The possibility or
idea is employed as a method for observing actual existence; and in
the light of what is discovered the possibility takes on concrete
existence. It becomes less of a mere idea, a fancy, a wished-for
possibility, and more of an actual fact. Invention proceeds, and at
last we have the telegraph, the telephone, first through wires, and
then with no artificial medium. The concrete environment is
transformed in the desired direction; it is idealized in fact and not
merely in fancy. The ideal is realized through its own use as a tool or
method of inspection, experimentation, selection and combination of
concrete natural operations.
Let us pause to take stock of results. The division of the world into
two kinds of Being, one superior, accessible only to reason and ideal
in nature, the other inferior, material, changeable, empirical,
accessible to sense-observation, turns inevitably into the idea that
knowledge is contemplative in nature. It assumes a contrast
between theory and practice which was all to the disadvantage of
the latter. But in the actual course of the development of science, a
tremendous change has come about. When the practice of
knowledge ceased to be dialectical and became experimental,
knowing became preoccupied with changes and the test of
knowledge became the ability to bring about certain changes.
Knowing, for the experimental sciences, means a certain kind of
intelligently conducted doing; it ceases to be contemplative and
becomes in a true sense practical. Now this implies that philosophy,
unless it is to undergo a complete break with the authorized spirit of
science, must also alter its nature. It must assume a practical
nature; it must become operative and experimental. And we have
pointed out what an enormous change this transformation of
philosophy entails in the two conceptions which have played the
greatest rôle in historic philosophizing—the conceptions of the real
and ideal respectively. The former ceases to be something ready-
made and final; it becomes that which has to be accepted as the
material of change, as the obstructions and the means of certain
specific desired changes. The ideal and rational also ceased to be a
separate ready-made world incapable of being used as a lever to
transform the actual empirical world, a mere asylum from empirical
deficiencies. They represent intelligently thought-out possibilities of
the existent world which may be used as methods for making over
and improving it.
Philosophically speaking, this is the great difference involved in the
change from knowledge and philosophy as contemplative to
operative. The change does not mean the lowering in dignity of
philosophy from a lofty plane to one of gross utilitarianism. It
signifies that the prime function of philosophy is that of rationalizing
the possibilities of experience, especially collective human
experience. The scope of this change may be realized by considering
how far we are from accomplishing it. In spite of inventions which
enable men to use the energies of nature for their purposes, we are
still far from habitually treating knowledge as the method of active
control of nature and of experience. We tend to think of it after the
model of a spectator viewing a finished picture rather than after that
of the artist producing the painting. Thus there arise all the
questions of epistemology with which the technical student of
philosophy is so familiar, and which have made modern philosophy in
especial so remote from the understanding of the everyday person
and from the results and processes of science. For these questions
all spring from the assumption of a merely beholding mind on one
side and a foreign and remote object to be viewed and noted on the
other. They ask how a mind and world, subject and object, so
separate and independent can by any possibility come into such
relationship to each other as to make true knowledge possible. If
knowing were habitually conceived of as active and operative, after
the analogy of experiment guided by hypothesis, or of invention
guided by the imagination of some possibility, it is not too much to
say that the first effect would be to emancipate philosophy from all
the epistemological puzzles which now perplex it. For these all arise
from a conception of the relation of mind and world, subject and
object, in knowing, which assumes that to know is to seize upon
what is already in existence.
Modern philosophic thought has been so preoccupied with these
puzzles of epistemology and the disputes between realist and
idealist, between phenomenalist and absolutist, that many students
are at a loss to know what would be left for philosophy if there were
removed both the metaphysical task of distinguishing between the
noumenal and phenomenal worlds and the epistemological task of
telling how a separate subject can know an independent object. But
would not the elimination of these traditional problems permit
philosophy to devote itself to a more fruitful and more needed task?
Would it not encourage philosophy to face the great social and moral
defects and troubles from which humanity suffers, to concentrate its
attention upon clearing up the causes and exact nature of these evils
and upon developing a clear idea of better social possibilities; in
short upon projecting an idea or ideal which, instead of expressing
the notion of another world or some far-away unrealizable goal,
would be used as a method of understanding and rectifying specific
social ills?
This is a vague statement. But note in the first place that such a
conception of the proper province of philosophy where it is released
from vain metaphysics and idle epistemology is in line with the origin
of philosophy sketched in the first hour. And in the second place,
note how contemporary society, the world over, is in need of more
general and fundamental enlightenment and guidance than it now
possesses. I have tried to show that a radical change of the
conception of knowledge from contemplative to active is the
inevitable result of the way in which inquiry and invention are now
conducted. But in claiming this, it must also be conceded, or rather
asserted, that so far the change has influenced for the most part
only the more technical side of human life. The sciences have
created new industrial arts. Man's physical command of natural
energies has been indefinitely multiplied. There is control of the
sources of material wealth and prosperity. What would once have
been miracles are now daily performed with steam and coal and
electricity and air, and with the human body. But there are few
persons optimistic enough to declare that any similar command of
the forces which control man's social and moral welfare has been
achieved.
Where is the moral progress that corresponds to our economic
accomplishments? The latter is the direct fruit of the revolution that
has been wrought in physical science. But where is there a
corresponding human science and art? Not only has the
improvement in the method of knowing remained so far mainly
limited to technical and economic matters, but this progress has
brought with it serious new moral disturbances. I need only cite the
late war, the problem of capital and labor, the relation of economic
classes, the fact that while the new science has achieved wonders in
medicine and surgery, it has also produced and spread occasions for
diseases and weaknesses. These considerations indicate to us how
undeveloped are our politics, how crude and primitive our education,
how passive and inert our morals. The causes remain which brought
philosophy into existence as an attempt to find an intelligent
substitute for blind custom and blind impulse as guides to life and
conduct. The attempt has not been successfully accomplished. Is
there not reason for believing that the release of philosophy from its
burden of sterile metaphysics and sterile epistemology instead of
depriving philosophy of problems and subject-matter would open a
way to questions of the most perplexing and the most significant
sort?
Let me specify one problem quite directly suggested by certain
points in this lecture. It has been pointed out that the really fruitful
application of the contemplative idea was not in science but in the
esthetic field. It is difficult to imagine any high development of the
fine arts except where there is curious and loving interest in forms
and motions of the world quite irrespective of any use to which they
may be put. And it is not too much to say that every people that has
attained a high esthetic development has been a people in which the
contemplative attitude has flourished—as the Greek, the Hindoo, the
medieval Christian. On the other hand, the scientific attitude that
has actually proved itself in scientific progress is, as has been
pointed out, a practical attitude. It takes forms as disguises for
hidden processes. Its interest in change is in what it leads to, what
can be done with it, to what use it can be put. While it has brought
nature under control, there is something hard and aggressive in its
attitude toward nature unfavorable to the esthetic enjoyment of the
world. Surely there is no more significant question before the world
than this question of the possibility and method of reconciliation of
the attitudes of practical science and contemplative esthetic
appreciation. Without the former, man will be the sport and victim of
natural forces which he cannot use or control. Without the latter,
mankind might become a race of economic monsters, restlessly
driving hard bargains with nature and with one another, bored with
leisure or capable of putting it to use only in ostentatious display and
extravagant dissipation.
Like other moral questions, this matter is social and even political.
The western peoples advanced earlier on the path of experimental
science and its applications in control of nature than the oriental. It
is not, I suppose wholly fanciful, to believe that the latter have
embodied in their habits of life more of the contemplative, esthetic
and speculatively religious temper, and the former more of the
scientific, industrial and practical. This difference and others which
have grown up around it is one barrier to easy mutual
understanding, and one source of misunderstanding. The philosophy
which, then, makes a serious effort to comprehend these respective
attitudes in their relation and due balance, could hardly fail to
promote the capacity of peoples to profit by one another's
experience and to co-operate more effectually with one another in
the tasks of fruitful culture.
Indeed, it is incredible that the question of the relation of the real
and the ideal should ever have been thought to be a problem
belonging distinctively to philosophy. The very fact that this most
serious of all human issues has been taken possession of by
philosophy is only another proof of the disasters that follow in the
wake of regarding knowledge and intellect as something self-
sufficient. Never have the real and the ideal been so clamorous,
so self-assertive, as at the present time. And never in the history of
the world have they been so far apart. The world war was carried on
for purely ideal ends:—for humanity, justice and equal liberty for
strong and weak alike. And it was carried on by realistic means of
applied science, by high explosives, and bombing airplanes and
blockading marvels of mechanism that reduced the world well nigh
to ruin, so that the serious-minded are concerned for the perpetuity
of those choice values we call civilization. The peace settlement is
loudly proclaimed in the name of the ideals that stir man's deepest
emotions, but with the most realistic attention to details of economic
advantage distributed in proportion to physical power to create
future disturbances.
It is not surprising that some men are brought to regard all idealism
as a mere smoke-screen behind which the search for material profit
may be more effectually carried on, and are converted to the
materialistic interpretation of history. Reality is then conceived as
physical force and as sensations of power, profit and enjoyment; any
politics that takes account of other factors, save as elements of
clever propaganda and for control of those human beings who have
not become realistically enlightened, is based on illusions. But others
are equally sure that the real lesson of the war is that humanity took
its first great wrong step when it entered upon a cultivation of
physical science and an application of the fruits of science to the
improvement of the instruments of life—industry and commerce.
They will sigh for the return of the day when, while the great mass
died as they were born in animal fashion, the few elect devoted
themselves not to science and the material decencies and comforts
of existence but to ideal things, the things of the spirit.
Yet the most obvious conclusion would seem to be the impotency
and the harmfulness of any and every ideal that is proclaimed
wholesale and in the abstract, that is, as something in itself apart
from the detailed concrete existences whose moving possibilities it
embodies. The true moral would seem to lie in enforcing the tragedy
of that idealism which believes in a spiritual world which exists in
and by itself, and the tragic need for the most realistic study of
forces and consequences, a study conducted in a more scientifically
accurate and complete manner than that of the professed Real-
politik. For it is not truly realistic or scientific to take short views, to
sacrifice the future to immediate pressure, to ignore facts and forces
that are disagreeable and to magnify the enduring quality of
whatever falls in with immediate desire. It is false that the evils of
the situation arise from absence of ideals; they spring from wrong
ideals. And these wrong ideals have in turn their foundation in the
absence in social matters of that methodic, systematic, impartial,
critical, searching inquiry into real and operative conditions which
we call science and which has brought man in the technical realm to
the command of physical energies.
Philosophy, let it be repeated, cannot solve the problem of the
relation of the ideal and the real. That is the standing problem of
life. But it can at least lighten the burden of humanity in dealing with
the problem by emancipating mankind from the errors which
philosophy has itself fostered—the existence of conditions which are
real apart from their movement into something new and different,
and the existence of ideals, spirit and reason independent of the
possibilities of the material and physical. For as long as humanity is
committed to this radically false bias, it will walk forward with
blinded eyes and bound limbs. And philosophy can effect, if it will,
something more than this negative task. It can make it easier for
mankind to take the right steps in action by making it clear that a
sympathetic and integral intelligence brought to bear upon the
observation and understanding of concrete social events and forces,
can form ideals, that is aims, which shall not be either illusions or
mere emotional compensations.
Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists And Engineers Adrian Sandu
CHAPTER VI
THE SIGNIFICANCE OF LOGICAL
RECONSTRUCTION
Logic—like philosophy itself—suffers from a curious oscillation. It is
elevated into the supreme and legislative science only to fall into the
trivial estate of keeper of such statements as A is A and the
scholastic verses for the syllogistic rules. It claims power to state the
laws of the ultimate structure of the universe, on the ground that it
deals with the laws of thought which are the laws according to which
Reason has formed the world. Then it limits its pretensions to laws
of correct reasoning which is correct even though it leads to no
matter of fact, or even to material falsity. It is regarded by the
modern objective idealist as the adequate substitute for ancient
ontological metaphysics; but others treat it as that branch of rhetoric
which teaches proficiency in argumentation. For a time a superficial
compromise equilibrium was maintained wherein the logic of formal
demonstration which the Middle Ages extracted from Aristotle was
supplemented by an inductive logic of discovery of truth that Mill
extracted from the practice of scientific men. But students of
German philosophy, of mathematics, and of psychology, no matter
how much they attacked one another, have made common cause in
attack upon the orthodox logics both of deductive proof and
inductive discovery.
Logical theory presents a scene of chaos. There is little agreement
as to its subject-matter, scope or purpose. This disagreement is not
formal or nominal but affects the treatment of every topic. Take such
a rudimentary matter as the nature of judgment. Reputable
authority can be quoted in behalf of every possible permutation of
doctrine. Judgment is the central thing in logic; and judgment is not
logical at all, but personal and psychological. If logical, it is the
primary function to which both conception and inference are
subordinate; and it is an after-product from them. The distinction of
subject and predicate is necessary, and it is totally irrelevant; or
again, though it is found in some cases, it is not of great importance.
Among those who hold that the subject-predicate relationship is
essential, some hold that judgment is an analysis of something prior
into them, and others assert that it is a synthesis of them into
something else. Some hold that reality is always the subject of
judgment, and others that reality is logically irrelevant. Among
those who deny that judgment is the attribution of predicate to
subject, who regard it as a relation of elements, some hold that the
relation is internal, some that it is external, and others that it is
sometimes one and sometimes the other.
Unless logic is a matter of some practical account, these
contrarieties are so numerous, so extensive, and so irreconcilable
that they are ludicrous. If logic is an affair of practical moment, then
these inconsistencies are serious. They testify to some deep-lying
cause of intellectual disagreement and incoherency. In fact,
contemporary logical theory is the ground upon which all
philosophical differences and disputes are gathered together and
focussed. How does the modification in the traditional conception of
the relation of experience and reason, the real and ideal affect logic?
It affects, in the first place, the nature of logic itself. If thought or
intelligence is the means of intentional reconstruction of experience,
then logic, as an account of the procedure of thought, is not purely
formal. It is not confined to laws of formally correct reasoning apart
from truth of subject-matter. Neither, on the contrary, is it concerned
with the inherent thought structures of the universe, as Hegel's logic
would have it; nor with the successive approaches of human thought
to this objective thought structure as the logic of Lotze, Bosanquet,
and other epistemological logicians would have it. If thinking is the
way in which deliberate reorganization of experience is secured, then
logic is such a clarified and systematized formulation of the
procedures of thinking as will enable the desired reconstruction to
go on more economically and efficiently. In language familiar to
students, logic is both a science and an art; a science so far as it
gives an organized and tested descriptive account of the way in
which thought actually goes on; an art, so far as on the basis of this
description it projects methods by which future thinking shall take
advantage of the operations that lead to success and avoid those
which result in failure.
Thus is answered the dispute whether logic is empirical or
normative, psychological or regulative. It is both. Logic is based on a
definite and executive supply of empirical material. Men have been
thinking for ages. They have observed, inferred, and reasoned in all
sorts of ways and to all kinds of results. Anthropology, the study of
the origin of myth, legend and cult; linguistics and grammar; rhetoric
and former logical compositions all tell us how men have thought
and what have been the purposes and consequences of different
kinds of thinking. Psychology, experimental and pathological, makes
important contributions to our knowledge of how thinking goes on
and to what effect. Especially does the record of the growth of the
various sciences afford instruction in those concrete ways of inquiry
and testing which have led men astray and which have proved
efficacious. Each science from mathematics to history exhibits typical
fallacious methods and typical efficacious methods in special subject-
matters. Logical theory has thus a large, almost inexhaustible field of
empirical study.
The conventional statement that experience only tells us how men
have thought or do think, while logic is concerned with norms, with
how men should think, is ludicrously inept. Some sorts of thinking
are shown by experience to have got nowhere, or worse than
nowhere—into systematized delusion and mistake. Others have
proved in manifest experience that they lead to fruitful and enduring
discoveries. It is precisely in experience that the different
consequences of different methods of investigation and ratiocination
are convincingly shown. The parrot-like repetition of the distinction
between an empirical description of what is and a normative account
of what should be merely neglects the most striking fact about
thinking as it empirically is—namely, its flagrant exhibition of cases
of failure and success—that is, of good thinking and bad thinking.
Any one who considers this empirical manifestation will not complain
of lack of material from which to construct a regulative art. The
more study that is given to empirical records of actual thought, the
more apparent becomes the connection between the specific
features of thinking which have produced failure and success. Out of
this relationship of cause and effect as it is empirically ascertained
grow the norms and regulations of an art of thinking.
Mathematics is often cited as an example of purely normative
thinking dependent upon a priori canons and supra-empirical
material. But it is hard to see how the student who approaches the
matter historically can avoid the conclusion that the status of
mathematics is as empirical as that of metallurgy. Men began with
counting and measuring things just as they began with pounding
and burning them. One thing, as common speech profoundly has it,
led to another. Certain ways were successful—not merely in the
immediately practical sense, but in the sense of being interesting, of
arousing attention, of exciting attempts at improvement. The
present-day mathematical logician may present the structure of
mathematics as if it had sprung all at once from the brain of a Zeus
whose anatomy is that of pure logic. But, nevertheless, this very
structure is a product of long historic growth, in which all kinds of
experiments have been tried, in which some men have struck out in
this direction and some in that, and in which some exercises and
operations have resulted in confusion and others in triumphant
clarifications and fruitful growths; a history in which matter and
methods have been constantly selected and worked over on the
basis of empirical success and failure.
The structure of alleged normative a priori mathematics is in truth
the crowned result of ages of toilsome experience. The metallurgist
who should write on the most highly developed method of dealing
with ores would not, in truth, proceed any differently. He too selects,
refines, and organizes the methods which in the past have been
found to yield the maximum of achievement. Logic is a matter of
profound human importance precisely because it is empirically
founded and experimentally applied. So considered, the problem of
logical theory is none other than the problem of the possibility of the
development and employment of intelligent method in inquiries
concerned with deliberate reconstruction of experience. And it is
only saying again in more specific form what has been said in
general form to add that while such a logic has been developed in
respect to mathematics and physical science, intelligent method,
logic, is still far to seek in moral and political affairs.
Assuming, accordingly, this idea of logic without argument, let us
proceed to discuss some of its chief features. First, light is thrown by
the origin of thinking upon a logic which shall be a method of
intelligent guidance of experience. In line with what has already
been said about experience being a matter primarily of behavior, a
sensori-motor matter, is the fact that thinking takes its departure
from specific conflicts in experience that occasion perplexity and
trouble. Men do not, in their natural estate, think when they have no
troubles to cope with, no difficulties to overcome. A life of ease, of
success without effort, would be a thoughtless life, and so also
would a life of ready omnipotence. Beings who think are beings
whose life is so hemmed in and constricted that they cannot directly
carry through a course of action to victorious consummation. Men
also do not tend to think when their action, when they are amid
difficulties, is dictated to them by authority. Soldiers have difficulties
and restrictions in plenty, but qua soldiers (as Aristotle would say)
they are not notorious for being thinkers. Thinking is done for them,
higher up. The same is too true of most workingmen under present
economic conditions. Difficulties occasion thinking only when
thinking is the imperative or urgent way out, only when it is the
indicated road to a solution. Wherever external authority reigns,
thinking is suspected and obnoxious.
Thinking, however, is not the only way in which a personal solution
of difficulties is sought. As we have seen, dreams, reveries,
emotional idealizations are roads which are taken to escape the
strain of perplexity and conflict. According to modern psychology,
many systematized delusions and mental disorders, probably
hysteria itself, originate as devices for getting freedom from
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PPTX
C programming language tutorial
DOCX
c++ notes.docx BASIC C++ PROGRAMMING NOTES
PPTX
C_Progragramming_language_Tutorial_ppt_f.pptx
DOCX
Complete c programming presentation
PDF
Over View of C language ( by dennid richi)
PDF
PART-1 Over View of C language ( engineering)
PPT
Mba Ebooks ! Edhole
PPT
Mba Ebooks ! Edhole
C programming language tutorial
c++ notes.docx BASIC C++ PROGRAMMING NOTES
C_Progragramming_language_Tutorial_ppt_f.pptx
Complete c programming presentation
Over View of C language ( by dennid richi)
PART-1 Over View of C language ( engineering)
Mba Ebooks ! Edhole
Mba Ebooks ! Edhole

Similar to Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists And Engineers Adrian Sandu (20)

PPTX
Introduction to c
DOCX
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
DOCX
Project 2 MARIE Start code at bottom of document1. IntroductionT.docx
PPTX
basic C PROGRAMMING for first years .pptx
PDF
Introduction to Input/Output Functions in C
PDF
A Project Based Lab Report On AMUZING JOKE
DOC
Comp 122 lab 7 lab report and source code
DOC
Cosc 1436 java programming/tutorialoutlet
PPT
Introduction to Basic C programming 01
PPTX
Python Programming Full Course || Beginner to Intermediate || Bangla (বাংলা) ...
PDF
Fortran 90 Basics
PPTX
programming for problem solving in C and C++.pptx
DOCX
Specification of the sequ commandCopyright © 2013 Bart Masse.docx
PDF
qb unit2 solve eem201.pdf
PPT
CInputOutput.ppt
PDF
C notes.pdf
PPTX
C Programming Language Tutorial for beginners - JavaTpoint
PPT
pengenalan mengenai computer dan programming
PDF
C Programming Assignment
DOCX
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
Introduction to c
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
Project 2 MARIE Start code at bottom of document1. IntroductionT.docx
basic C PROGRAMMING for first years .pptx
Introduction to Input/Output Functions in C
A Project Based Lab Report On AMUZING JOKE
Comp 122 lab 7 lab report and source code
Cosc 1436 java programming/tutorialoutlet
Introduction to Basic C programming 01
Python Programming Full Course || Beginner to Intermediate || Bangla (বাংলা) ...
Fortran 90 Basics
programming for problem solving in C and C++.pptx
Specification of the sequ commandCopyright © 2013 Bart Masse.docx
qb unit2 solve eem201.pdf
CInputOutput.ppt
C notes.pdf
C Programming Language Tutorial for beginners - JavaTpoint
pengenalan mengenai computer dan programming
C Programming Assignment
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
Ad

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Classroom Observation Tools for Teachers
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Structure & Organelles in detailed.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Types and Its function , kingdom of life
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
GDM (1) (1).pptx small presentation for students
Classroom Observation Tools for Teachers
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
VCE English Exam - Section C Student Revision Booklet
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Structure & Organelles in detailed.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
01-Introduction-to-Information-Management.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Types and Its function , kingdom of life
Ad

Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists And Engineers Adrian Sandu

  • 1. Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists And Engineers Adrian Sandu download https://ebookbell.com/product/introduction-to-fortran-95-and- numerical-computing-a-jumpstart-for-scientists-and-engineers- adrian-sandu-28374602 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Introduction To Programming With Fortran With Coverage Of Fortran 90 95 2003 2008 And 77 2nd Edition Ian Chivers https://ebookbell.com/product/introduction-to-programming-with- fortran-with-coverage-of-fortran-90-95-2003-2008-and-77-2nd-edition- ian-chivers-2521034 Introduction To Programming With Fortran With Coverage Of Fortran 90 95 2003 2008 And 77 3rd Edition Ian Chivers https://ebookbell.com/product/introduction-to-programming-with- fortran-with-coverage-of-fortran-90-95-2003-2008-and-77-3rd-edition- ian-chivers-5234568 Introduction To Programming Using Fortran 9520032008 Version 3051 Ed Jorgensen https://ebookbell.com/product/introduction-to-programming-using- fortran-9520032008-version-3051-ed-jorgensen-10466018 Introduction To Modern Fortran For The Earth System Sciences 1st Edition Dragos B Chirila https://ebookbell.com/product/introduction-to-modern-fortran-for-the- earth-system-sciences-1st-edition-dragos-b-chirila-4974234
  • 3. Introduction To Programming With Fortran 4th Edn Ian Chivers Jane Sleightholme https://ebookbell.com/product/introduction-to-programming-with- fortran-4th-edn-ian-chivers-jane-sleightholme-49848242 Introduction To Programming With Fortran Ian D Chivers Bsc Pgced https://ebookbell.com/product/introduction-to-programming-with- fortran-ian-d-chivers-bsc-pgced-4239444 Introduction To Programming With Fortran 4th Ian Chivers Jane Sleightholme https://ebookbell.com/product/introduction-to-programming-with- fortran-4th-ian-chivers-jane-sleightholme-7164316 Introduction To Programming With Fortran Ian Chivers Jane Sleightholme https://ebookbell.com/product/introduction-to-programming-with- fortran-ian-chivers-jane-sleightholme-59265710 Introduction To Computational Economics Using Fortran Hans Fehr Fabian Kindermann https://ebookbell.com/product/introduction-to-computational-economics- using-fortran-hans-fehr-fabian-kindermann-10920622
  • 5. Lecture Notes Introduction to Fortran 95 and Numerical Computing A Jump-Start for Scientists and Engineers Adrian Sandu Computer Science Department, Michigan Technological University Reproduction of (parts of) this document is permissible only with author's consent. August 23, 2001
  • 6. 2 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. Acknowledgements The present lecture notes are based in part on the following excellent books: Fortran 90 Programming" by Ellis, Philips and Lahey, Addison-Wesley publishing company, 1994; Fortran 90 Course Notes" by A.C. Marshall, U. Liverpool, 1997; Elementary numerical analysis" by K.E. Atkinson, 2nd edition, John Wiley & Sons, Inc, 1993.
  • 7. Contents 1 A quick tour of Fortran 95 5 2 The Building Blocks of a Fortran Application 23 3 More on Flow Control 41 4 Computer Representation of Numbers and Computer Arithmetic 47 5 Applications Part I. 77 6 Intrinsic Functions 83 7 Input and Output. 89 8 Arrays 99 9 More on Procedures 115 10 Parametrised Intrinsic Types 129 11 Derived Types 133 12 Pointers and Targets 137 13 Elements of object-oriented programming 149 14 Code Performance 151 15 Linear Systems of Algebraic Equations 157 16 Linear Least Squares 175 3
  • 8. 4 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 17 Nonlinear Equations 181 18 Polynomial Interpolation 189 19 Numerical Integration 191 20 Piecewise Polynomial Interpolation. Splines. 197 21 Taylor Polynomials 207
  • 9. Chapter 1 A quick tour of Fortran 95 1.1 Program Form The main program unit begins with the keyword program (optional), followed by the program name (also otional); it ends with the keyword end (required), followed by program Name Prog (optional). program <name> declarations executable code end [ program <name> ] Open a le hello.f90. Type the following hello world" program: ! my rst Fortran program program hello print , 'Hello World!' end program hello Compile it with f90 hello.f90. Run the resulting code with a.out. 1.2 Free vs. Fixed Formats In Fortran 95 the code layout is obeys the following rules, which describe the free source form. statements can begin in any column; multiple statements on a line are allowed; they have to be separated by semicolon ; an exclamation mark ! in any column is the beginning of a comment; the rest of the line is ignored by the compiler; a statement can be continued on the following line by appending a sign on the current line. For example, the above code fragment could be written in free source form as 5
  • 10. 6 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. ! This is free form temp = x; x = y; y = temp ! Swap x and y write(6,) 'x and y are =', x,y ! Print x and y For back-compatibility with Fortran 77, Fortran 90 accepts a xed source form. In short, the xed source form requirements are: all lines of code start in the 7th (or higher) column; the rst 6 columns are reserved for labels, contin- uation characters, etc. each statement is written on a separate line (i.e., statements are separated by newlines); a statement can be continued on the next line by writing (any) character in the 5th column of the new line; comment lines start with a C in the rst column. Fixed format was born in 1950's, when each line of code was punched on a paper card (punched card). For debugging and maintaining the code it was clearly easier to have one statement per card. When running, a punched card had to be aligned, checked if it is a new statement or a continuation of the last, if it is a comment, etc. - lots of information stored in the rst 6 columns. (A million-line code, quite common today, on punched cards, needed a truck to be carried from one computer to another). For example, a fragment of a Fortran 90 program in xed source form (in fact, Fortran 77 program) can be: C This is xed form C Swap x and y temp = x x = y y = temp C Print x and y write(6,) 'x and y are =', x,y Our compiler (f90) will consider the program to be in xed source format if the source le has the extension .f (for example, my program.f). The compiler will consider the program to be in free source format if the source le has the extension .f90 (for example, my program.f90). Note that a free format source in a .f le may result in compilation errors. 1.3 Declaration of Variables 1.3.1 Memory Organization. Variables Discuss how memory is organized Variables correspond to storage locations in memory. They are denoted by identi ers, which obey the following restrictions: contain up to 31 characters; the rst character must be a letter; names are case-insensitive (no distiction between upper and lower case).
  • 11. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 7 At the beginning of the program, we declare the types of the variables. Declarations reserve the necessary number of bytes in memory and bind the variable name (identi er) to the address of the reserved memory space; the content of the reserved bytes will hold the variable's value. There are 6 intrinsic (default) data types in Fortran: character, logical, integer, real (single precision), double precision and complex. The last four types are re erred to as numeric data types. 1.3.2 Integers. Declaration: integer I, J, K or integer :: I, J, K An integer can be declared and initialized with integer :: I = 1 Normally, when the program is loaded in memory, the contents of the declared variables are unde ned (some compilers may set them to 0 by default). With initialization, the content of the variables when loading is set to the prescribed values. An integer constant (whose value cannot be changed later in the program) can be declared with integer MAXIMUM parameter (MAXIMUM=340) or with integer, parameter :: MAXIMUM=340 The plain form of declaration, and the two-statement parameter declaration come from F77, and is legal in F90 also. The double colon :: form is speci c to F90. Note that we have to use the double colon form whenever more than one attribute is given for the variable (e.g., when is integer and parameter, i.e. constant) or when the variable is initialized. 1.3.3 Characters. Declaration: character C or character :: C For a string of characters, we can specify the length and (optionally) initialize it as character(len=7) :: LOGIN Again we see that, if we want to specify more than one attribute (here, character and length) the double colon form is needed. We can have constant (PARAMETER) characters/strings, in which case we use the declaration character(len=8), parameter :: LOGIN=johndoe
  • 12. 8 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. (the F77 two-statement form is also acceptable). Here the initialization value is 6-character long, so it will be padded by 2 blanks to t the declared length. Similarly, if the initialization value was too long, it would have been truncated to the declared length. Alternatively, we may let the character variable assume the length of the initialization string with character(len=), parameter :: LOGIN=johndoe, PASSWORD=michigantech Here LOGIN will be 7-character, and PASSWORD 12-character long. The following equivalent form of declaration is also accepted (for back-compatibility with F77): character8 :: LOGIN The LEN attribute can be overriden by a attribute in a string declaration as follows: character(len=8) :: LOGIN, PASSWORD12 Here LOGIN is a string of 8 characters, but PASSWORD is a string of 12 characters. Note that a string is a scalar; in particular it is NOT an array of characters. For example, it is possible to declare a 1010 matrix whose elements are 6-character long strings: character(len=6), dimension(10,10) :: A A string can be split accross lines by adding an ampersand both at the end of the current line and at the beginning of the next. For example michig nantech 1.3.4 Reals. The declarations real X, Y, PI or real :: X, Y, PI state that X, Y and PI are single precision oating point variables. A real parameter (whose value cannot be changed subsequently) may be declared with real PI parameter (PI=3.141592) or with real, parameter :: PI=3.141592 The double colon form is needed for more than one attribute (see above), or for declarations plus initial- izations real :: X = 21.5g Application: circle area and perimeter.
  • 13. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 9 program rst implicit none ! disable implicit d. real::R,Pi,a,p Pi=3.1415926 print, 'Please give radius:' read, R a=PiR ! is exponentation p=2.0PiR print, 'Area=',a,' Perimieter=',p end program rst 1.3.5 Double Precision. The declarations double precision X, Y, PI or double precision :: X, Y, PI state that X, Y and PI are double precision oating point variables. A similar discussion as for REAL type holds. 1.3.6 Complex Fortran allows for complex numbers also. They are declared as complex Z, W or complex :: Z, W A Fortran complex variable is (and is stored as) a pair of real (single precision oating point) variables (the real and the imaginary part, of course). For example, to declare and initialize the complex constant 2 + 3i we use complex, parameter :: Z=(2.0,3.0) 1.3.7 Logical. Logical (Boolean) variables are declared as logical Q, P or logical :: Q, P They can take only (one of) two possible values: true or false (written, in Fortran notation, .TRUE. and .FALSE.). A declaration with initialization may look like logical :: Q=.TRUE., P=.FALSE.
  • 14. 10 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 1.3.8 General Form of Declarations The general form a F90 declaration is htypei[;hattribute listi] :: [;hvariablei[= hvaluei]] attribute list contains attributes like PARAMETER, SAVE, INTENT, POINTER, TARGET, DI- MENSION, etc. Any object may be given any number of attributes, provided they are compatible with each other. 1.3.9 Implicit declarations In Fortran implicit declarations are allowed. Suppose we did not declare the variables I, J, X, Y but used them somewhere in the program. The Fortran compiler will not complain; rather, it will automatically declare I, J as integers and X, Y as reals. The rule is that undeclared variables which have the rst letter I, J, K, L, M or N are considered INTEGER-s, and undeclared variables which start in A through H and O through Z are considered REAL-s. The automatic declarations based on implicit types are called implicit declarations. Some fourty years ago programmers found it cumbersome to explicitly declare all the variables all the time ! In F90 implicit declarations are permitted, but undesirable. In general, their use is a very bad program- ming habit, as it can mask programming errors, and can negatively impact future software development and maintainance. For example, a misspelling of a variable name will result in a new variable declaration, which can be further assigned etc, with the user being totally unaware. An example (from A.C. Marshall) is do30i = 1.100 statements 30 continue Instead of a DO loop, because of the misprints, we will end up with a new real variable, do30i. In consequence, we will always disable the implicit declarations by placing the command implicit none as the rst line after any USE statements (i.e. before the declarations sequence). With this command in place, the existence of variables that are not explicitly declared will lead to a copilation error. 1.4 Assignment An expression of the form Z = Z + 2.0 fetches the value of Z from memory, adds 2.0, and stores the result at the same memory location Z. In short, Znew = Zold +2:0. Note that the assignment = has a totally di erent meaning than mathematical equality (here, the mathematical relation Z = Z +2:0 is an equation without solution).
  • 15. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 11 1.5 Intrinsic Numerical Operations NUMERIC TYPE :: a,b NUMERIC TYPE :: [a] hnumerical operatori b Fortran, like any other language, de nes several operators that act on numerical type variables. The addition, subtraction, multiplication, division and exponentiation operators are denoted + ; ; ; = ; and respectively. Nothe that addition and subtraction can be monadic (e.g. +2:1 or 2:1) or dyadic (e.g. 2:1 3:4) operators. Also note that we can raise a positive real number to a real power, e.g. 2:33:14, but not ( 2:3)3:14. In arithmetic expressions di erent numerical types can be used (will see later), but we usually cannot mix numerical and character, or numerical and logical variables. 1.6 Literal Constants We can use value constants directly in the statements; such values are called literal constants. For example, a number can be raised to an integer power Y = X4 ; Z = X( 6) Both exponent values 4, 6 are written directly in the source text. For real constants, we need to use either decimal point notation or scienti c notation (similar to oating point notation base 10: we have a mantissa, followed by an exponent of 10; the expenent is preceded by E) Y = X + 21.54 or Y = X + 2.154E+1 For double precision constants, we always use scienti c notation, but now the exponent marker E is replaced by D, from double: Y = X + 21.54D0 or Y = X + 2.154D+1 For complex literal constants we need to specify a (real part, imaginary part) pair. To assign the number Z = 2:25+4:1i we do Z = ( 2.25, 4.1 ) Logical constants can take one of two values, written as Q = .TRUE. or Q = .FALSE. Finally, character literal constants are delimited by single or double quotes C = 'A' or C = A If the delimiter is part of the string, the convention is to write it twice inside the string, for example C = 'OMalley'
  • 16. 12 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 1.7 Relational Operators numerical type :: a,b logical :: a relational operator b F77/F90 F90 Meaning .GT. greater than .GE. = g.t. or equal to .LE. = l.t. or equal to .LT. less than .NE. = = not equal to .EQ. == equal to Relational operators compare the values of two numerical operands and deliver a logical result (.TRUE. or .FALSE.). Note that for complex operands only .EQ. and .NE. can be used. Example. a = 12.0 if ( a.GE.10.0 ) then ... The expression a .GE. 10 evaluates to .TRUE. 1.8 Intrinsic Logical Operations logical :: a,b logical :: [a] logical operator b F90 Meaning .NOT. monadic logical negation .AND. logical AND (T.AND.T=T, else F) .OR. logical OR (F.OR.F=F, else T) .EQV. true, if both operands have same value .NEQV. true, if operands have di erent values Example. real :: a, b logical :: q1, q2 q1 = (.NOT.q2) .AND. (a.GT.b)g 1.9 Intrinsic Character Operations 1.9.1 Substrings character(len=), parameter :: school=michigantech
  • 17. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 13 Expression Value school(2:4) ich school(:8) michigan school(9:) tech school(4) error (string is scalar) school(4:4) h (correct form) 1.9.2 Concatenation character(len=), parameter :: state=michigan, name=tech character(len=12) :: school school = state // name ! produces michigantech 1.10 Operator Precedence user-de ned monadic highest (tightest binding) ;= . monadic +; . dyadic +; . == . relational operators (.GT. etc.) . .NOT. . .AND. . .OR. . .EQV., .NEQV. (weakest binding) user-de ned dyadic lowest For multiple same-level operators evaluation is done left to right (except for ). Paranthesis can alter the order of evaluation, and are recommended anyway for clarity. Sometimes paranthesis can make subtle di erences, e.g. A=B C 6= A=(B C) or A = 229; B = 1:999999230; C = 1:999998230; X = A +B C ! X = 1; (over ow) Y = A +(B C) ! Y = correct value Homework 0.1 Add all possible paranthesis to indicate the order of evaluation for :NOT:A:AND:B:EQV:C:OR:D:AND:E:OR:x:GT:y:AND:y:EQ:z 1.11 Intrinsic Functions The most widely used functions are part of the Fortran system (are intrinsic to Fortran). This means that the each Fortran system provides high quality implementations of these functions. We can call them without
  • 18. 14 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. linking to any mathematical library. Give some examples here. 1.12 Controlling the ow of the program 1.12.1 Conditional execution IF Blocks permit conditional execution of a part of program. Syntax: [hnamei :] IF(hlogical expri ) THEN hthen blocki [ ELSEIF(hlogical expri ) THEN [hnamei] helseif blocki ] [ ELSE [hnamei] helse blocki ] END IF [hnamei] Both ELSEIF and ELSE are optional. There can be any number of ELSEIF branches. First the IF-s hlogical expriession is evaluated, and if .TRUE. the statements in the hthen blocki are executed and control is then transferred to the rst statement following END IF. If .FALSE., the ELSEIF- s hlogical expriessions are evaluated succesively, until the rst one is found to hold .TRUE. Then the corresponding helseif blocki statements are executed. If none of the ELSEIF-s hlogical expriessions is found .TRUE., the ELSE branch is taken (if present). If the ELSE branch is not present the control is transferred to the rst instruction after END IF. 1.12.2 Examples (Discuss control ow diagram with rombs and rectangles) if (i .gt. 17) then print*, i 17 ! end if if (i .gt. 17) then print*, i 17 ! else print*, i = 17 ! end if if (i .gt. 17) then print*, i 17 ! elseif (i .eq. 17) then print*, i = 17 !
  • 19. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 15 elseif (i .eq. 16) then print*, i = 16 ! else print*, i 16 ! end if Example of IF block use: solving a quadratic equation. program quadratic eqn 1 implicit none real::a,b,c ! coe of the quadratic eqn. real::d ! determinant real::x1,x2 ! solutions , if real (cases I, II) real::xre,xim ! real and imaginary parts of solutions (case III) !read in the coeÆcients print, 'Please give quadr. eqn. coe . a, b, c:' read,a,b,c d=b2 4.0ac ! check the cases and treat them seperate if (d.GT.0.0) then x1=( b SQRT(d))/(2.0a) x2=( b+SQRT(d))/(2.0a) print,'The eqn. has two disctinct real roots: ', 'x1=',x1,' x2=',x2 else if(d.EQ.0.0) then x1= b/(2.0a) print, 'The eqn. has two equal roots: ', 'x1=x2=',x1 else ! d0 xre= b/(2.0a) xim=SQRT( d)/(2.0a) print, 'The eqn. has two complex conjugate roots: ', xre,'+/ ',xim,'i' end if end program quadratic eqn 1 Example ofcomplex numbers use: solving a quadratic equation, Solution no. 2. program quadratic eqn 2 implicit none real::a,b,c complex::d,x1,x2,sd !read in the coeÆcients print,'Please give a, b, c:' read,a,b,c !compute discriminant d=b2 4ac !sqrt(d): since d is complex, sqrt is complex sd=SQRT(d) ! compute roots: x1=( b+sd)/(2.0a) x2=( b sd)/(2.0a) print,'Roots are' print,'X1=',x1
  • 20. 16 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. print,'X2=',x2 end program quadratic eqn 2 1.12.3 Repetitive action DO Loops permit repetitive action. Syntax: DO hDO vari = hn expr1i;hn expr2i[;hn expr3i] hexec stmtsi END DO The loop can be named and the body can contain EXIT or CYCLE statements. The loop is worked out as follows 1. Evaluatenumericalexpressionshn expr1i, hn expr2iand, if present, hn expr3i. If notpresent, hn expr3i is assumed to have the default value = 1. 2. Initialize the Do variable, DO var hn expr1i. 3. The iteration count is computed with the formula #it = max bhn expr2i hn expr1ihn expr3i hn expr3i c;0 Note that both the number of iterations #it and the stride hexpr3i are evaluated before execution of the loop begins. Subsequent value changes will have no in uence on the iteration process. If #it 0 the execution cycle starts. At the end of each cycle, the iteration counter is decremented by 1 #it #it 1 and the DO variable (DO var) is modi ed by adding the stride DO var DO var +hn expr3i The iteration continues if #it 0, otherwise exits. As a consequence, at the end of the iterations, DO var might assume a value di erent from hn expr2i. Modifying the DO var inside the body loop is prohibited (and results in a compilation error). For example, a missing stride hexpr3i is set by default to 1. The code do i=1,9 print, i end do will execute the loop exactly 11 times, and will produce the output 1;2;3;:::9. do i=1,9,2 print, i end do
  • 21. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 17 will produce the output 1;3;5;:::9. A negative stride is possible, the code do i=9,1, 2 print, i end do will produce the output 9;7;5:::1. The loop do i=9,1,1 print, i end do will produce no output since initially #it = 0. Also, the loop do i=1,9, 1 print, i end do nn will produce no output since initially #it = max( 8;0) = 0. EXIT statement nishes the innermost loop; however, with named do loops, it can exit the indicated loop, regardless of its nesting level. Similarly, CYCLE outer cycles back to the outer loop, whereas a plain CYCLE would have cycled back to the inner loop. outer: do i=1,9 inner: do j=i,9 print*, before: ,i, j if (j .gt. 3) cycle outer ! go to outer: do print*, before: ,i, j if (j .gt. 6) exit outer ! go to outer: do print*, after: ,i,j end do inner end do outer 1.13 Application to DO loops: Fahrenheit to Celsius Write a program that converts the temperature from Fahrenheit degrees to Celsius degrees (centigrades). The steps are: 1. Problem formulation 2. Algorithm 3. Implementation 4. Run, and if the result is wrong, loop back. program temp conv implicit none integer::n ! no. of temperatures to convert
  • 22. 18 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. real::f,c ! temp. values in F,C integer::i ! loop counter print,'No. of conversions=' read,n do i=1,n print,'Fahrenheit temp. no ',i,'=' read,f c=9.0/5.0(f 32) print,f,' F is ', c ,' C' end do end program temp conv 1.14 Problems 1. write a program that reads in the radius and computes the area of a circle; 2. extend the program to test whether the area is negative; if so just STOP. This introduces IF blocks, and logical expressions; 3. extend the program to read 5 radii; this introduces a DO loop and integer variables; CYCLE and EXIT. 4. extend the code to rst read all 5 radii and then compute all 5 areas; this introduces arrays. The dimension (N=5) is a PARAMETER. 1.15 Input and Output 1.15.1 Standard (keyboard/console) read, R print, V print, 'R = ', R or print*, R = , R 1.15.2 File I/O Opening les In Fortran, les are designated by unit number, which is an integer number. Values from 0 to 6 are reserved for standard I/O, standard error, etc. Usually user-de ned les have unit numbers of 10 and above. Sometimes we need to read from/ write into user de ned les. In order for Fortran to be aware of the existence of user-de ned les, we need to OPEN them (this is somehow similar to variable declaration). For example, the statement open( unit=10, file='data.txt', action='READ')
  • 23. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 19 will open the le named 'data.txt'; the mode declaration states that this is an input (read-only) le; the statement will allocate unit number 10 to the le 'data.txt'; from now on, all READ(10,*) will read in data from this le. The statement open( unit=11, file='results.txt', action='WRITE')nendftabularg will open the le named 'results.txt'; if not present, will create one; the mode declaration states that this is an output (writeable) le; the statement will allocate unit number 11 to the le 'results.txt'; from now on, all WRITE(11,*) will write data into this le. The list of arguments must be of standard intrinsic types (unless explicit format is used). Each WRITE statement puts the arguments on a new line; non-advancing WRITE is possible, but we need to use formats. Note that the statement, as is, will wipe out the content of results.txt, should it previously exist. It is possible to declare action='readwrite' for les which are both I/O. Also not recommended, the two statements above can be abbreviated as open( 10, 'data.txt', 'READ') open( 11, 'results.txt ', ' WRITE') The opened les may be closed with close(10) close(11) The unit number can then be re-used (for a di erent le) in a subsequent OPEN statement. Read and Write The le read function has two parameters read( unit=unit no, fmt=format label ) [ list of arguments ] Each parameter can be replaced by a , with the meaning default unit or default format. We will talk later about formats. The call read(5,) R, V reads two reals from unit number 5 in default format. Unit 5 is prede ned, and is the standard input (keyboard, unless redirected). Thus, an equivalent formulation is read(,) R, V The le write function is very similar, write( unitn no, format label ) [ list of arguments ] Each parameter can be replaced by a (defaults). The call write(6,) R, V
  • 24. 20 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. writes two reals onto unit number 6 in default format. Unit 6 is prede ned, and is the standard output (monitor, unless redirected). Thus, an equivalent formulation is write(,) R, V The list of arguments must be of standard intrinsic types (unless explicit format is used). Each READ statement reads the arguments from a new line; non-advancing READ is possible, but we need to use formats. 1.15.3 Application Modify the Fahrenheit to Celsius program to read the temperature (ÆF) from one le, and output it to another le (ÆC). program temp conv implicit none integer::i,n real::f,c integer::in=10,out=11 ! unit numbers !open the les open(unit=in,file='fahr.data',action='read') open(unit=out,file='celsius.data',action='write') !read and write how many temperatures read(unit=in,fmt=) n write(unit=out,fmt=) n do i=1,n read(unit=in,fmt=) f c=9.0/5.0(f 32) write(unit=out,fmt=) c print,i,' F=',f,' is C=',c end do end program temp conv The open, close, read and write functions can be checked if they performed ok using the IOSTAT param- eter. In our case we check whether end-of- le was reached and if so we exit the loop. This way there is no need to have the number of temperatures as the rst number in the le. program temp conv 3 implicit none real::f,c integer::iostatus !open the data le , F open(unit=10,file='fahr2.data',action='read',iostat=iostatus) !check if the le was opened properly if(iostatus.NE.0) then print,'Data file could not be opened' stop ! terminates the program end if !open the result le open(unit=11,file='celsius2.data',action='write',iostat=iostatus) !check if the le opened properly if(iostatus.NE.0) then print,'Output file cannot be opened' stop
  • 25. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 21 end if do read(unit=10,fmt=,iostat=iostatus) f !check if this is a valid read if(iostatus.NE.0) then print,'end of file reached' exit end if c=5.0/9.0(f 32) write(unit=11,fmt=) c end do end program temp conv 3 1.16 Arrays Arrays are collection of elements of similar type. This data structure allows to implement mathematical objects like vectors, matrices and tensors. To declare an array with 3 real elements we use real, dimension(3) :: v or real :: v(3) real v(3) Particular entries of the array can be accessed with an index, running from 1 through the number of entries. v(1)=1.0; v(2)=2.0; v(3)=3.0 One can assign values to all elements of v at once using an array constructor. A constructor is a list of scalar values delimited by (/ ... /). For example the same initialization of v can be achieved using v = (/ 1.0, 2.0, 3.0 /) An even more compact initialization is achieved using an implicit do loop: v = (/ (i , i=1,3) /) In Fortran jargon the one-dimensional object v is called a rank-1 array (its entries are accessed using a single index). One can de ne multi-dimensional arrays as well. A rank-2 array can be de ned for example as real, dimension(2,3) :: A or real :: A(2,3) real A(2,3)) A particular element is now accessed using two indices: A(i,j) where 1 i 2 and 1 j 3. One can initialize a rank-n arrayusing constructors. The list of entriesin a constructoris one-dimensional; we need to map this one-dimensional list onto the k-dimensional array. This is done using the intrinsic function reshape. For example, we can initialize the 6 entries of A using A = reshape ( (/ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 /), (/ 2, 3 /) )
  • 26. 22 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. The rst argument of the reshape function is the constructor, the second is another constructor containing the shape of A. Reshape initializes the entries of A in column-wise order; the result of the above operation is A = 1:0 3:0 5:0 2:0 4:0 6:0 : Arrays can be used as arguments for input/output purposes. For example read, A will (expect to) read 6 numbers from the console and assign the values to elements of A in column-wise order. Similarly, print, A prints the elements of A one after another in column-wise order. 1.16.1 Application Vector times matrix multiplication. program mvproduct implicit none real, dimension(3) :: V real, dimension(2,3) :: A real,dimension(2) :: W integer :: i,j print,'please give V(1:3)' read,V print,'Please give A (1:2,1:3)'; read,a ! The list of numbers from console is 1 dimensional, and is ! reshaped by the read function to the shape of A in column wise order. ! compute the matrixVector product do i=1,2 ! for each entry of w, compute w(i) w(i)=0.0 do j=1,3 w(i)=w(i)+a(i,j)V(j) end do end do !print eVerything. print,'A=' do i=1,2 print,(A(i,j),j=1,3) ! use implicit do loop to print all elements in row i end do print,'V=',V print,'W=',w ! end program mvproduct
  • 27. Chapter 2 The Building Blocks of a Fortran Application 2.1 Program Units An F95 application will usually consist of several program units. One of them is the main program unit, where the execution of the program starts, and where, usually, it ends if everything went all right with the computation. The main program unit is delimited by the following keywords: program hprogram namei ... end program pname The other four types of program units de ned in F95 are external functions, external subroutines, modules and block data units. The beginnings and ends of these units are designated by the following syntaxes, respectively: function hfunction namei ... end function hfunction namei subroutine hsubroutine namei ... end subroutine hsubroutine namei module hmodule namei ... end module hmodule namei block data hblock data namei ... end block data hblock data namei 23
  • 28. 24 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. As a general principle, the programming task is divided into smaller subtasks, which are then individually solved. Di erent program units can implement di erent subtasks; programming units are standalone, in the sense that they do not depend upon implementation details in the body of other program units; the units communicate to each other via speci c interfaces, so one unit only needs to be aware of the interfaces to other program units. 2.2 External Procedures External procedures are parametrised blocks of code that perform a speci c task; this section of code is written once, and can be re ered to as many times as needed; are independent units which may be compiled separately; communicate with other program units via arguments, returned values (functions only), and global variables (to be discussed another lecture); can be used as arguments in other procedure calls. Advantages avoid code duplication (when same task appears several times in our program); lead to modularization of programs. The general principle of dividing the problem into subproblems, and managing the subproblems separately, can be naturally implemented using procedures; make software reusable (pieces can be used later in a di erent context); In F95 there are 2 types of external procedures, 1. functions, and 2. subroutines. 2.3 External Functions The syntax of a function declaration is [htypei] FUNCTIONhfcn namei([hformal(dummy) argsi]) hdeclare formal(dummy) argsi hdeclare local objectsi hexecutable statementsi END[FUNCTION[hfcn namei]] For example, suppose we want to declare a function that receives the three coordinates of a cartesion vector x,y,z and returns the euclidian norm of the vector, r = p x2 +y2 +z2 (this is also called the 2-norm). The arguments x,y,z are REAL, and so is the returned value r. The declaration could then be
  • 29. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 25 ! function that computes norm 2 real=type of the returned value real function norm 2(x,y,z) !x,y,z are dummy arguments implicit none !scope=body of the function real::x,y,z !dummy args declaration norm 2=SQRT(x2+y2+z2) !function name behaves like a variable !holding the return value end function norm 2 !function for norm 1 real function norm 1(x,y,z) implicit none real::x,y,z norm 1=abs(x)+abs(y)+abs(z) end function norm 1 !function for norm in nity real function norm inf(x,y,z) implicit none real::x,y,z norm inf=max(abs(x),abs(y),abs(z)) end function norm inf !the main program program norms implicit none real::a,b,c real,external::norm 1,norm 2,norm inf print,'Please give coordinates a,b,c.' read,a,b,c print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args print,'The 1 norm= ',norm 1(a,b,c) print,'The inf norm= ',norm inf(a,b,c) end program norms Note that the function name hfcn namei (norm 2) behaves like a variable; when the function terminates, this variable holds the result of the function (the return value of the function). The type of function is the type of the returned result, i.e. the type of the result variable (norm2). This type is declared explicitly as a pre x to the function name; in our example, real function norm2(x,y,z). Alternatively, this declaration can be mixed with the other declarations, for example function norm2(x,y,z) implicit none real :: x, y, z, norm2 Either form is valid, and one declaration should always be given (otherwise the compiler will signal an error). The variables x,y,z are called formal (dummy) arguments. They hold the input data for the function. When the function is invoked, they will be replaced by actual values. The calling program also declares the type of the function, padded with the EXTERNAL attribute. For example, the calling program might read in the coordinates and print the 2-norm of the vector:
  • 30. 26 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. program print norm implicit none real, external :: norm2 real :: a, b, c print, 'input~3~coordinates:' read,a,b,c print,'the norm is',norm2(a,b,c) end program print norm The declaration REAL, EXTERNAL :: norm2 tells the main program that norm2 is an external function which returns a REAL result. Of course, the compiler can gure out itself that norm2 is a function by seeing the name norm2 followed by paranthesis and the list of arguments at the place of call. Therefore, the EXTERNAL attribute is not really necessary here, and we can simplify the declaration to REAL :: norm2. However, it is good programming practice to have the EXTERNAL attribute, and I advise you to keep it whenever external functions (or procedures) are used. In passing, we note that there are instances when the name of the external function appears without the argument list - e.g. when the function name itself is an argument in another function call. In these instances, the EXTERNAL attribute is mandatory, since the compiler cannot distinguish between a function name and a variable name. Again, I advise you to give the EXTERNAL attribute all the time: the code is more readable, and you do not have to remember the detailed requirements for using this attribute. The argument passing mechanism uses stacks. A stack is a memory structure which can be accessed (for both writting (push) and reading (pop)) from the top only. An example of a stack is: [see picture]. 2.4 Actual arguments, formal (dummy) arguments and local vari- ables The function is invoked by its name, followed by a list of actual arguments. When the call is issued, in a special memory structure, called the program stack, 5 new locations are reserved; the addresses of the 3 arguments a,b,c are pushed, in this order, into the stack. The 4th location contains the address of the real variable norm2, which was declared in the main program and is expected to hold the result of the function calculation. The 5th location is dedicated to the local variable loc, about which we will talk later. The control is then transferred from the caller (here, the main program) to the called function norm2. The function sees the stack; from the function perspective, on the stack are (top to bottom): result variable address, argument z address, argument y address, and argument x address. The formal (dummy) names x,y,z are therefore just aliases for the actual variable names, to be used inside the function body (we say that, when the funcion is called, formal (dummy) variables are replaced by actual variables). It is therefore required that the order in which the actual arguments are supplied is precisely the order of formal (dummy) arguments in the function declaration. Moreover, the type of nth actual argument should coincide exactly with the type its omologue (nth ) formal (dummy) argument. The norm calculation is performed and the result stored in norm2 (the function knows the address of this variable also!). At this point the control is returned to the main program. Here the function call norm2(a,b,c) is simply replaced by the value found in the result variable norm2, and the computations in the main program proceed further.
  • 31. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 27 ? 7 H H H H H H H H H H H H H H H Y ? ? PROGRAM ... END PROGRAM ... FUNCTION END FUNCTION norm2(x,y,z) norm2 norm2(a,b,c) @z=@c loc @x=@a @y=@b @norm2 Stack As presented here, the argument passing is said to be done by reference, since references to, rather than values of arguments are put on the stack. Note that, in practice, the situation is more complicated; the actual parameter-passing mechanism can be somewhat di erent than what we show here. This is the case, for example, when the function is invoked with literal constant arguments (perfectly legal in F95) print, norm2(1.0, 2.0, 3.0) Nevertheless, the above discussion is useful to understand the inner logic of the F95 function declaration and function call syntax. The variable loc is called a local variable. Its scope is the body of the function. When the function is called, space is allocated on the stack for loc; at this point the memory location does not carry any useful information. When the control returns to the main program (the caller), the stack pointer is reset to its previous value, wiping out all the information on stack; loc is therefore destroyed when the function is exited. loc does not exist between function calls. Obviously, a new function call means a new incarnation of loc, unrelated to the previous one; in particular, loc cannot remember its value from the previous call. Note that IMPLICIT NONE should be used in any function declaration just as it is used in the main program. 2.4.1 Implicit Interfaces Implicit interfaces are the old, F77 way of communication. Separate procedures are desired to be as indepen- dent as possible from one another (so that they can be written, compiled and maintained independently); in particular, a procedure is totally ignorant of how a di erent procedure looks like. Consider our norm example. The main program knows that norm2 is an external function that returns a real value, but it has no information about the arguments. Special problems arise when procedures call each other; the caller has very limited knowledge on the
  • 32. 28 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. called procedure; it passes a list of actual argument addresses to the called procedure; the called procedure retrieves this addresses in order, and assumes they are the addresses of the formal (dummy) arguments. The disadvantage of this approach is that the compiler is able to perform only limited consistency checks. In F77, it is easy to make mistakes undetectable by the compiler when working with argument lists. Consider, for example, the following subroutine ! function that computes norm 2 real=type of the returned value real function norm 2(x,y,z) !x,y,z are dummy arguments implicit none !scope=body of the function real::x,y,z !dummy args declaration norm 2=SQRT(x2+y2+z2) !function name behaves like a variable !holding the return value end function norm 2 !function for norm 1 real function norm 1(x,y,z) implicit none real::x,y,z norm 1=abs(x)+abs(y)+abs(z) end function norm 1 !function for norm in nity real function norm inf(x,y,z) implicit none real::x,y,z norm inf=max(abs(x),abs(y),abs(z)) end function norm inf !the main program program norms implicit none real::a,b,c real,external::norm 1,norm 2,norm inf print,'Please give coordinates a,b,c.' read,a,b,c print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args print,'The 1 norm= ',norm 1(a,b,c) print,'The inf norm= ',norm inf(a,b,c) end program norms The accidental switch of arguments cannot be detected by the compiler and produces most curious results.
  • 33. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 29 2.5 Subroutines An external subroutine a program unit that does all the communication with the rest of the world via arguments (and global variables); it does not return a value. The syntax of a subroutine declaration is SUBROUTINEhsbr namei([hformal(dummy) argsi]) hdeclare formal(dummy) argsi hdeclare local objectsi hexecutable statementsi END[SUBROUTINE[hsbr namei]] For example, suppose we want to declare a subroutine that receives the three coordinates of a cartesion vector x,y,z and computes the 2-norm of the vector, r = p x2 +y2 +z2 (this is also called the 2-norm). The arguments x,y,z are REAL, and so is the computed value r. The declaration could then be subroutine norm2s(x,y,z,r) implicit none real :: x,y,z,r r = sqrt(x2+y2+z2) end subroutine norm2s The calling program invokes the subroutine using call norm2s(a,b,c,d) The CALL statement builds the argument stack and passes control to the subroutine; when END SUBROUTINE is encountered, the control is returned to the calling program, at the rst statement after CALL. Unlike functions, subroutines communicate with the calling program via arguments (or global variables) only - they do NOT return a value associated with the subroutine's name. For example, the main program might read in the coordinates and print the 2-norm of the vector: program print norm implicit none external :: norm2s real :: a, b, c, d print*, input~3~coordinates: read,a,b,c call norm2s(a,b,c,d) print*,the norm is,d end program print norm The declaration EXTERNAL :: norm2s tells the main program that norm2 is an external subroutine (we do NOT have any type declaration associated with the name!). Again, in this particular context the declaration is super uos, but, since it will be mandatory in other contexts, and since it improves readability, I strongly recommend its use. The actual arguments a,b,c,d replace the formal (dummy) arguments x,y,z,r (in this order) at the time of call. The type and order of actual arguments should match exactly the type and order of their omologue formal (dummy) arguments. An IMPLICIT NONE statement should be given in each subroutine, just as it is given in the main program.
  • 34. 30 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 2.6 Comments Procedures for most common programming tasks have already been written and are available for us to use (many times for free!). One example is the set of intrinsic functions in F95. Another example are the standard libraries for numerical computations. BLAS (Basic Linear Algebra Subroutines) is a collection of modules that perform matrix and vector calculations. LAPACK is a complete set of subroutines for solving numerical linear algebra problems. Any time we have a programming task, and need to write a piece of code, it is advisable to check whether a standard subroutine, in a standard collection, performs the same task for us. This cuts down programming time; cuts down the likelihood of programming errors; usually, enhances performance; and, of course, enhances software maintainability. If we are to write our own procedures from scratch, here is some expert (and free!) advice, from A.C. Marshall: 1. keep the procedures under 50 lines long, for a simple control structure; 2. make procedures as exible as possible, to allow for software reuse; 3. pass as many variables as possible as actual arguments, and rely as little as possible on global storage or host association; 4. give procedures meaningful names, and plenty of comments; 5. there is absolutely no point in reinventing the wheel - use standard libraries whenever they o er subroutines which solve the required task. 2.7 Modules Modules are special program units, delimited by the following syntax: module hmodule namei ... end module hmodule namei A module contains only declarations of di erent entities; it can contain no executable statements. Other program units (functions, subroutines, main program or even other modules) can attach the module, and by doing so they can see (have access to) the entities declared in the module. Therefore, the functionality of a module is to declare objects and to make them available to other program units. In this regard, they are di erent from procedures (which are supposed to perform some computations, some I/O, etc). We can attach a module to a program unit by inserting use hmodule namei as the rst statement in the program unit (right after the header, and right before any declaration). Jargon: when a program unit USEs a module, it has access to the (public) objects declared in the module; we say that the module entities are visible within that program unit by use-association. Note that, in particular, modules can be attached to other modules, which in their turn can be attached to other modules etc. In this situation we have to be careful not to create a circular de nition, which is of
  • 35. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 31 course prohibited. An example of a circular, hence mistaken de nition, is: module 2 uses module 1, module 3 use module 2 and module 1 uses module 3. What we said here is not the whole story with modules: it suÆces for now, but we will study more in the future. 2.8 Scope of Variables The scope of an entity is the part of the program where the entity is visible. The main program, a function or a procedure are scoping units; an entity declared inside a scoping unit is visible throughout the unit. In particular, a variable declared in the main program or in a procedure has the body of the pro- gram/pocedure as its scope. A variable is local (has local scope) if its scope is that of a scoping unit. A variable whose scope is the entire program has global scope. Some variables can be seen by multiple program units - by extension we will also talk about global scope. Global storage (global scope variables) can be implemented using modules or common blocks. This is discussed later in this chapter. 2.9 Lifetime of Variables A variable is alive when its name is associated with a memory location. A variable is alive during the execution of the program unit that declared it: variables declared in the main program live throughout the execution of our application; local variables (declared inside a function or subroutine and which are not formal (dummy) arguments or global variables) are automatically allocated each time the procedure is called (allocation on function stack) and automatically deallocated when the procedure returns. They are called automatic variables. Their value is destroyed when the procedure returns; each call means a new variable is created. SAVE attribute makes the variable static. It is allocated in a static part of the memory and is never deallocated (during the execution of our program). In particular static variables preserve their value between calls. Here is an example of a subroutine which counts how many times it has been called. The variable icount is static due to the initialization. ! function that computes norm 2 real=type of the returned value real function norm 2(x,y,z) !x,y,z are dummy arguments implicit none !scope=body of the function real::x,y,z !dummy args declaration norm 2=SQRT(x2+y2+z2) !function name behaves like a variable !holding the return value end function norm 2 !function for norm 1 real function norm 1(x,y,z) implicit none
  • 36. 32 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. real::x,y,z norm 1=abs(x)+abs(y)+abs(z) end function norm 1 !function for norm in nity real function norm inf(x,y,z) implicit none real::x,y,z norm inf=max(abs(x),abs(y),abs(z)) end function norm inf !the main program program norms implicit none real::a,b,c real,external::norm 1,norm 2,norm inf print,'Please give coordinates a,b,c.' read,a,b,c print,'The 2 norm= ',norm 2(a,b,c) !a,b,c are actual args print,'The 1 norm= ',norm 1(a,b,c) print,'The inf norm= ',norm inf(a,b,c) end program norms Instead of initializing it, one can make the variable ilocal static using integer, save :: ilocal save ilocal A single SAVE statement not followed by a list of variables has the e ect of declaring static(saving) all local entities in a program unit that can be saved (note that formal (dummy) arguments and automatic arrays cannot be saved). 2.10 Global Storage We have seen so far that procedures communicate with the outside world via arguments and via returned values (functions); all other variables declared are local, their scope is the body of the procedure only. This fact has the advantage that procedures can be written without any knowledge of the program unit from which they will be called - all that is required is that the interface is known. However, for large programs, this will lead to very long argument lists, which can be a serious drawback when programming (how about writing a routine with 10,000 arguments, and then calling it from 1,000 diferent places with di erent actual arguments?). It is therefore necessary to have a mechanism for global storage, that is, to have variables that are visible from di erent program units, without being included in the argument lists. In F95, modules provide this extra mechanism of communication. Variables declared in a module are visible within all procedures and programs which USE that particular module.
  • 37. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 33 2.10.1 Circle Example We want to write two functions, which calculate the perimeter and the area of a circle, respectively. Both functions need the value of . We de ne this value in a module: module de ne pi implicit none real, parameter :: pi = 3.1415926 end module de ne pi By USE-ing the module in both functions, we make sure that they see the same value of . The main program reads in the value of the radius and prints the perimeter and the area of the circle. real function perimeter(r) use de ne pi implicit none real :: r perimeter = 2.0pir end function perimeter real function area(r) use de ne pi implicit none real :: r area = pirr end function area program circle implicit none real :: r real, external :: perimeter, area print, 'radius =' read, r print,'area = ',area(r) print,'perimeter = ',perimeter(r) end program circle 2.10.2 Taylor Approximation of the Exponential Consider a program which compares the Taylor approximation of the exponential with the intrinsic function. We de ne a module Coeff which declares the order n of the approximation; the maximal order allowed n max=10 and a vector b of coeÆcients for the Taylor polynomial. Note that, in the de nition, we include speci cally the range to be 0:n max; this means that b will contain n max+1 elements, indexed from 0 to n max. module coe integer :: n integer, parameter :: n max = 10 real, dimension(0:n max) :: b end module coe program approx use coe implicit none real :: x integer :: i external taylor exp real, external :: eval ! print*, please input order (n = 10) read, n n = min(n, n max) call taylor exp ! do i= 3,3 x= 2.0i print, x,) exp=,exp(x),
  • 38. 34 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. ; taylor=, eval(x) end do end program approx subroutine taylor exp ! calculate the rst n coeÆcients ! in the taylor approx. of exp use coe implicit none integer :: i b(0) = 1.0 do i=1,n b(i) = b(i 1)/real(i) end do end subroutine taylor exp real function eval(x) ! evaluate the order n ! polyn. with coeÆcients b(i) use coe implicit none real, intent(in) :: x integer :: i eval = b(n) do i = n 1,0, 1 eval = b(i)+xeval end do end function eval The subroutine Taylor exp USEs the module Coeff. As a consequence, it has access to all three global variables n, n max and b. Note that this subroutine has no arguments, which is legal in F90, but does all the communication with the ouside world via the global variables in the module Coeff. Taylor exp calculates the rst n+1 coeÆcients in the Taylor series for the exponential function, and stores them in b(0) through b(n). The function Eval has just one input argument, x. It also USEs the module Coeff, hence it seesn, n max and b. The function evaluates the value of the polynomial b(0)+b(1) x +::: +b(n) xn ; and returns this value to the calling program. It is easy to notice that a nested form evaluation algorithm is used. The main programalsoUSEsEval. Because of this, the variables in Eval exist aslong as the programruns; they are e ectively static variables (we will discussed in the future about this). The subroutine Taylor exp, the function Eval and the main program all have access to n, n max and b; any of them can read and write any of these variables; in this sense, n, n max and b are called global variables. We say that the scope of n, n max and b includes the main program, the subroutine and the function. The main program reads in the desired order of approximation n; then, sets it to n max if it is larger than this maximal value. When called, the subroutine Taylor exp lls in b(0) ... b(n) with the coeÆcients of the nth Taylor polynomial. Finally, Eval is called several times, with di erent arguments, and the results of the intrinsic function and this approximation are printed together, for comparison. Note that, once the coeÆcients b(0) ... b(n) have been calculated and stored, they can be subsequently used to obtain any number of approximate values Eval(x).
  • 39. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 35 Homework 0.2 Write a module and two subroutines PUSH and POP to simulate a stack; the module will allocate an 0:N MAX array, the memory space for the stack, and will contain a stack pointer (an integer to keep track of the current position in the stack). 2.11 F77 Global Storage. Storage Association. The default global storage facility in F77 are the COMMON blocks. It is likely that we will encounter them in older software; however, we encourage the use of modules, not COMMON blocks, whenever global storage is required. The above version of our example program can be reformulated with COMMON blocks as follows: program approx integer :: n real, dimension(0:10) :: b common /coe / n, b print*, please input order (n = 10) read, n n = min(n, 10) call taylor exp ! do i= 3,3 x= 2.0i print, x,) exp=,exp(x), ; taylor=, eval(x) end do end program approx subroutine taylor exp ! calculate the rst ! n coeÆcients in ! the taylor approx. of exp integer :: n real, dimension(0:10) :: b common /coe / n, b ! integer :: i b(0) = 1.0 do i=1,n b(i) = b(i 1)/real(i) end do end subroutine taylor exp real function eval(x) ! evaluate the order n ! polyn. with coeÆcients b(i) integer :: n real, dimension(0:10) :: b common /coe / n, b ! real, intent(in) :: x integer :: i
  • 40. 36 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. eval = b(n) do i = n 1,0, 1 eval = b(i)+xeval end do end function eval A common block declaration consists by the keyword COMMON, followed by the common block's name hcb namei (included between slashes); common blocks are recognized by their names within all program units, i.e. COMMON block names are, by default, global names (they have to di er from any program unit name). In the declaration, the name is followed by the list of variables stored in the COMMON block. COMMON=hcb namei= var1;var2;var3;::: All program units that invoke the common /coe / ... statement, for example, will have access to the common block /coeff/'s variables. Since we can have variables shared by multiple units, common blocks are a mean of implementing global storage. Note that an argument of a function or subroutine cannot be simultaneously a common block variable in the same procedure. Physically, a common block is a contiguous zone of memory (a block of memory) in which succesive chunks of bytes are allocated to succesive variables (i.e. to the variables speci ed in the de nition of the COMMON block). Speci cally, INTEGERs, REALs and LOGICALs are allocated 1 storage unit in the block, DOUBLE PRECISION and COMPLEX variables are given 2 storage units (1 unit is usually 4 bytes, but depends on the implementation). Characters are considered to have a di erent storage unit, incompatible with the numerical storage unit; they are therefore incompatible with the numerical types; chracter and numerical variables cannot be part of the same COMMON block. The memory block can be seen by any program unit which includes its declaration, being therefore COMMON to several program units.
  • 41. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 37 BB B B BBB L L LL L LLL n b(0) COEFF This storage scheme is also the main weakness of COMMON blocks. The reason is that the names of variables var1;var2 ::: are local to the program unit which declares them, while the COMMON block name is global. Thus, di erent program units can access the same common block, but can refer to the common block variables with di erent (local) names. Of course, what counts is the relative position of a variable within the block - the name is just a (local) alias for this position. Therefore, the types and the order of common block variables have to be the same, but their names can di er (pretty much like the list of formal (dummy) vs. the list of actual arguments). For example, consider the following subroutine which prints the rst two elements of the COMMON block COEFF. subroutine p2 integer :: n, p common /coe / n, p print, n, p end subroutine p2 The compiler cannot check that types of the succesive variables in COMMON blocks match for di erent common block de nitions; it will just check that local de nitions are consistent. Now, our intent was to have rst an integer (n), then a real number b(0); by mistake, we declared both integers, and the compiler cannot help us; in consequence, the 32 bits of the real number b(0) will be interpreted as the 32 bits of a signed integer (in two's complement) p; instead of 1.0 we obtain 1065353216. In addition, common blocks containing data of heterogeneous(di erent) types may lead to memory missalignments.
  • 42. 38 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 2.12 BLOCK DATA statements To initialize the variables in a COMMON BLOCK we can use the BLOCK DATA construct. For example, block data coe init integer :: n real, dimension(0:10) :: b common /coe / n, b data n /10/ data b /1.0000000000e+00, 1.0000000000e+00, 0.5000000000e+00, 0.1666666667e+00, 4.1666666667e 02, 8.3333333333e 03, 1.3888888889e 03, 1.9841269841e 04, 2.4801587302e 05, 2.7557319224e 06, 2.7557319224e 07/ end block data coe init initializes the elements of the (coeff) COMMON block variables to n=1, x(1) = 3.0, x(2) = 5.0. Note that a BLOCK DATA construct includes the COMMON block statement, and the de nitions of the COMMON block variables; also, it contains the DATA statements, which initialize the variables with the prescribed values (i.e. at compile time the allocated memory slots for the speci ed variables are written with the given initial values). The statement save /coe / makes the common block static storage; it will be kept in memory for the whole duration of the current execution (in practice most Fortran systems will automatically make all common blocks static, but we should not rely on this!). 2.13 Include les To avoid the problems of inconsistent common block declarations it is common practice to place the common blocks and their variable declarations in a le, and then to include the le in di erent program units which use the common block. For example, the le coe .cmm may contain integer :: n real, dimension(0:10) :: b common /coe / n, b and we may use include 'coe .cmm' This is equivalent to inserting (rewritting) the content of coe .cmm at each place where the le is included. We therefore avoid repeating the same declarations and are sure of the consistency. 2.14 More on Storage Association Fortran allows for a special, unnamed common block, called the blank COMMON block. It is declared as common // var 1, var 2, ..., var n
  • 43. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 39 Blank common block is useful when most, or a large number of routines, need to share same variables. Some special features of the blank common block are contained data is automatically static,and it cannot be initialized in a BLOCK DATA statement; the compiler is more permissive (e.g. it allows the blank common block to be invoked with a di erent number of variables in di erent program units). In F77 several entities (scalar or array) can be associated with the same memory location, using equivalence ( var 1, var 2 , ..., var n ) All the variables in the list are stored in the same memory locations, more exactly, their storage spaces start at the same address in the memory. EQUIVALENCE is usually used in conjunction with large common blocks, to identify the parts of the block for the current procedure. For example, a common block /VERY LONG/ can store 28 real arrays, containing a total of 15,421 real elements common /very long/ a(7311), b(121), ..., z(1272) Suppose in a procedure only the second array, B(121) is used; we can use the declaration real b(121) common /very long/ blk(15421) equivalence (b, blk(7312)) (we employed F77 syntax on purpose). Sometimes the results of EQUIVALENCE statements are hard to understand. For example real x, y(2), z complex c equivalence (x,y,c), (y(2), z) c = cmplx(1.0,2.0) has the e ect of setting y(1) x REAL(c) = 1.0 and y(2) z AIMAG(c) = 2.0.
  • 44. 40 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
  • 45. Chapter 3 More on Flow Control 3.1 Named IF and DO Blocks Naming IF blocks is mainly cosmetic, but is useful to improve readability when nested IF blocks are used (nesting can go to any depth!). For example lev0: if (a.gt.b) then print*, a is larger elseif (a.lt.b) then lev0 lev1: if (b.gt.c) then print*, b is larger elseif (b.lt.c) then lev1 lev2: if (c.gt.d) then print*, c is larger end if lev2 end if lev1 end if lev0 A similar discussion for DO loops. 3.2 The IF Statement Is a shorter form of an IF block, when neither the ELSEIFs nor the ELSE branches are present. Syntax: if (hlogical expressioni) statement If the hlogical expriession is .TRUE. then the (single) hstatementi is executed; if .FALSE., then control is just passed further. Note that the single hstatementi is usually a very powerfull instruction, like EXIT or GOTO. Homework 0.3 Write a program that reads 3 lengths (3 real numbers) and reports back if they can de ne a triangle; if yes, print a message if the de ned triangle is equilateral, isosoles, or arbitrary. 41
  • 46. 42 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 3.3 More on DO Loops The general syntax of a do loop is: [hnamei :]do hexec stmtsi end do [hnamei :] The body of the loop (hexec stmtsi) is delimited by DO and ENDDO keywords. A name can be associated with the DO loop. hexec stmtsi are executed as many times as required. As it stands the loop will cycle inde nitely; we have to append the loop with the proper mechanism to control the number of iterations. 3.3.1 Conditional EXIT do hexec stmts1i if ( hlogical expri) exit hexec stmts2i end do The hlogical expriession is evaluated at every sweep through the loop. If true, EXIT is executed, which (of course!) exits the loop and transfers control to the rst statement after END DO. Usually, EXIT is in either the rst or the last statement in the body of the loop, for improved readability. An EXIT statement outside the body of a loop is an error. Conditional EXIT loops are useful when we want the input data to control the number of iterations. For example, the Fahrenheit to Celsius program can read and convert temperatures until an unrealistic temperature, say 1000 or less, is read in. Try this example! 3.3.2 Conditional CYCLE do hexec stmts1i if ( hlogical expri) cycle hexec stmts2i end do If hlogical expriession is true, CYCLE is executed; it forcess control to bypass hexec stmts2i and to jump to the DO statement; the loop will then start the next iteration. A CYCLE statement outside the body of a loop is an error. For example, the Fahrenheit to Celsius program can skip the conversion of the temperatures that are unreasonably high, say 1000 or above. Try this example! 3.3.3 Exit and Cycle with named loops EXIT statement nishes the innermost loop; however, with named do loops, it can exit the indicated loop, regardless of its nesting level. Similarly, CYCLE outer cycles back to the outer loop, whereas a plain CYCLE would have cycled back to the inner loop. outer: do i=1,9
  • 47. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 43 inner: do j=i,9 print*, before: ,i, j if (j 3) cycle outer ! go to outer: do print*, before: ,i, j if (j 6) exit outer ! go to outer: do print*, after: ,i,j end do inner end do outer 3.3.4 Initial Test (DO...WHILE) Loop Syntax: do while hlogical expri hexec stmtsi end do The hlogical expriession is evaluated at the beginning of every iteration; the loop executes only if it holds .TRUE. Clearly, the operands of the hlogical expriession need to be modi ed during execution (otherwise the loop will either not execute or continue forever). Initial test loops are standard in most programming languages and have numerous applications. The DO...WHILE LOOP can be replaced with the functionally equivalent construction: DO; IFEXIT ... END DO. 3.4 SELECT CASE Syntax: [hnamei :] SELECT CASE (hcase expri ) [ CASE (hcase selectori) [hnamei] hexec stmtsi ] [ CASE DEFAULT [hnamei] hexec stmtsi ] END SELECT [hnamei] hcase expri must be a scalar of type INTEGER, LOGICAL or CHARACTER; hcase selectori can be a single value (.TRUE.) or a range (12 : 16); one cannot use an expression as case selector. hcase expri is evaluated and compared to the hcase selectoris, in order; when a match is found, the branch is taken and the corresponding hexec stmtsi executed. If no hcase selectori matches then the CASE DEFAULT branch is executed, if present. At the end of hexec stmtsi in the selected branch the control is passed to the rst statement following END SELECT.
  • 48. 44 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. A CASE SELECT function can be implemented with an IF ... ELSEIF... ENDIF construction; how- ever, the former needs a di erent expression to evaluate at each branch, and is therefore less eÆcient. Example: select case (i) case (:0) ; print*, i=0 case (1) ; print*, i=1 case default; print*, i=2 end select program season implicit none integer::month print,'Give month' read,month select case (month) case (12,1,2) print,'Month ',month,' is in winter' case(3:5) ! this is range from 3 to 5 print,'Month ',month,' is in spring' case(6:8) print,'Month ',month,' is in summer' case(9:11) print,'Month ',month,' is in fall ' case default print,'invalid month: ',month end select end program season 3.5 Exceptional Situations All the control ow constructs described so far enter the construct at only one place (IF, DO or SELECT CASE) and exit the construct at only one place also (END IF, END DO or END SELECT respectively). This enables the programmer to easily control the logic of the code. In some situations, it is convenient to have the possibility to exit the constructs at di erent places; for example, if an error in the data was detected, measures have to be taken right away, even if we are in the middle of several multiple nested DO loops. Fortran provides 3 di erent means to achieve this. 3.5.1 STOP The statement STOP immediately terminates the execution of the program. It is used when the program has detected an unrecoverable error. 3.5.2 RETURN RETURN is called from a subroutine, causing its execution to be terminated immediately and transferring the control back to the caller.
  • 49. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 45 3.5.3 GO TO Syntax: GOTO hstmt labeli or GO TO hstmt labeli A statement label (hstmt labeli) is a number of up to 5 digits (1:::99999), written in column 1 through 5 (this is inherited from the xed form). It is separated from the statement it labels by at least 1 blank. For example, 12345 PRINT*, Error 001 CONTINUE The statement GOTOhstmt labeli immediately transfers control to the statement labeled by hstmt labeli. IF (A .EQ. 0) GO TO 12345 ........ 12345 PRINT*, Error: A=0 ! Begin the recover-from-error strategy The hstmt labeli can be an integer expression, evaluated at run time. Except when needed to recover from error situations, we will avoid the use of GO TO, since it leads to unstructured programs. Experience over many years has shown [GOTO statements] to be the single biggest cause of bad pro- gramming habits and consequent programming errors. (T. Ellis, I. Philips, T. Lahey).
  • 50. 46 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing.
  • 51. Chapter 4 Computer Representation of Numbers and Computer Arithmetic 4.1 Binary numbers In the decimal system, the number 107.625 means 107:625 = 1102 +7100 +610 1 +210 2 +510 3 : Such a number is the sum of terms of the form fa digit times a di erent power of 10g - we say that 10 is the basis of the decimal system. There are 10 digits (0,...,9). All computers today use the binary system. This has obvious hardware advantages, since the only digits in this system are 0 and 1. In the binary system the number is represented as the sum of terms of the form fa digit times a di erent power of 2g. For example, (107:625)10 = 26 +25 +23 +21 +20 +2 1 +2 3 = (1101011:101)2 : Arithmetic operations in the binary system are performed similarly as in the decimal system; since there are only 2 digits, 1+1=10. 1 1 1 1 0 + 1 1 0 1 1 0 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 1 0 1 0 Decimal to binary conversion. For the integer part, we divide by 2 repeatedly (using integer division); the remainders are the successive digits of the number in base 2, from least to most signi cant. Quotients 107 53 26 13 6 3 1 0 Remainders 1 1 0 1 0 1 1 For the fractional part, multiply the number by 2; take away the integer part, and multiply the fractional part of the result by 2, and so on; the sequence of integer parts are the digits of the base 2 number, from 47
  • 52. 48 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. most to least signi cant. Fractional 0:625 0:25 0:5 0 Integer 1 0 1 Octal representation. A binary number can be easily represented in base 8. Partition the number into groups of 3 binary digits (23 = 8), from decimal point to the right and to the left (add zeros if needed). Then, replace each group by its octal equivalent. (107:625)10 = ( 1 101 011 : 101 )2 = (153:5)8 Hexadecimal representation. To represent a binary number in base 16 proceed as above, but now partition the number into groups of 4 binary digits (24 = 16). The base 16 digits are 0,...,9,A=10,...,F=15. (107:625)10 = ( 0110 1011 : 1010 )2 = (6B:A)16 1. Convert the following binary numbers to decimal, octal and hexa: 1001101101.0011, 11011.111001; 2. Convert the following hexa numbers to both decimal and binary: 1AD.CF, D4E5.35A; 3. Convert the following decimal numbers to both binary and hexa: 6752.8756, 4687.4231. 4.2 Memory The data and the programs are stored in binary format in computer's memory. Memory is organized in bytes, where 1 byte = 8 binary digits. In practice we use multiples of byte. 1 Kb 1024 bytes 210 bytes 1 Mb 1024 Kb 220 bytes 1 Gb 1024 Mb 230 bytes There are several physical memories in a computer; they form a memory hierarchy. Note that the physical chips for cache memory use a di erent technology than the chips for main memory; they are faster, but smaller and more expensive. Also, the disk is a magnetic storage media, a di erent technology than the electronic main memory; the disk is larger, cheaper but slower. Memory Type Size Access time Registers 8 bytes 1 clock cycle Cache, Level 1 126 Kb - 512 Kb 1 ns Cache, Level 2 512 Kb - 8 Mb 10 ns Main memory 8 Mb - 2 Gb 60 ns Hard drive 2 Gb - 40 Gb 10 ms 4.2.1 Characters in Memory Characters are letters of the alphabet, both upper and lower case, punctuation marks, and various other symbols. In the ASCII convention (American Standard Code for Information Interchange) one character uses 7 bits. (there are at most 27 = 128 di erent characters representable with this convention). As a consequence, each character will be stored in exactly one byte of memory.
  • 53. c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. 49 Homework 0.4 Implement the following program program test char character a, b a='s' write(6,) 'Please input b:' READ, b write(6,) a,b stop end Note how characters are declared and initialized. Run the program successfully. 4.2.2 The Memory Model When programming, we think of the main memory as a long sequence of bytes. Bytes are numbered sequentially; each byte is designated by its number, called the address. For example, suppose we have a main memory of 4 Gb; there are 232 bytes in the memory; addresses ranging from 0:::232 1 can be represented using 32 bits (binary digits), or (equiv.) by 8 hexa digits. Suppose we want to store the string john. With one character per byte, we need 4 successive memory locations (bytes) for the string. Each memory location has an address and a content. 'j' 'o' 'h' 'n' Content 1B56AF75 1B56AF74 1B56AF73 1B56AF72 Address When we declare a variable, the corresponding number of bytes is reserved in the memory; the name of the variable is just an alias for the address of the rst byte in the storage. 4.3 Reprentation of Signed Integers m binary digits (bits) of memory can store 2m di erent numbers. They can be positive integers between 00...00 = (0)10 and 11...11 = (2m 1)10. For example, using m = 3 bits, we can represent any integer between 0 and 7. If we want to represent signed integers (i.e. both positive and negative numbers) using m bits, we can use one of the following methods:
  • 54. 50 c Adrian Sandu, 1998-2001. Introduction to F95 and Numerical Computing. Sign/Magnitude representation. Reserve the rst bit for the signum (for example, let 0 denote positive numbers, and 1 negative numbers); the other m 1 bits will store the magnitude (the absolute value) of the number. In this case the range of numbers represented is 2m 1 +1 to +2m 1 1. With m = 3 there are 2 bits for the magnitude, di erent possible magnitudes, between 0 and 127; each of these can have a positive and negative sign. Note that with this representation we have both positive and negative zero. If we make the convention that the sign bit is 1 for negative numbers we have Number10 ([S]M)2 -3 [1]11 -2 [1]10 -1 [1]01 -0 [1]00 +0 [0]00 +1 [0]01 +2 [0]10 +3 [0]11 Two's complement representation. All numbers from 2m 1 to +2m 1 1 are represented by the smallest positive integer with which they are congruent modulo 2m. With m = 3, for example, we have Number10 (2C)10 (2C)2 -4 4 100 -3 5 101 -2 6 110 -1 7 111 0 0 000 1 1 001 2 2 010 3 3 011 Note that the rst bit is 1 for negative numbers, and 0 for nonnegative numbers. Biased representation. A number x 2 [ 2m 1 ;2m 1 1] is represented by the positive value x = x +2m 1 2 [0;2m 1]. Adding the bias 2m 1 gives positive results. Number10 (biased)10 (biased)2 -4 0 000 -3 1 001 -2 2 010 -1 3 011 0 4 100 1 5 101 2 6 110 3 7 111 The rst bit is 0 for negative numbers, and 1 for nonnegative numbers. 4.3.1 Integers in Memory Onebyteof memorycanstore28 = 256di erent numbers. Theycanbe positiveintegersbetween 00000000 = (0)10 and 11111111 = (255)10.
  • 55. Other documents randomly have different content
  • 56. are approached in which there is no movement at all, knowledge becomes really demonstrative, certain, perfect—truth pure and unalloyed. The heavens can be more truly known than the earth, God the unmoved mover than the heavens. From this fact follows the superiority of contemplative to practical knowledge, of pure theoretical speculation to experimentation, and to any kind of knowing that depends upon changes in things or that induces change in them. Pure knowing is pure beholding, viewing, noting. It is complete in itself. It looks for nothing beyond itself; it lacks nothing and hence has no aim or purpose. It is most emphatically its own excuse for being. Indeed, pure contemplative knowing is so much the most truly self-enclosed and self-sufficient thing in the universe that it is the highest and indeed the only attribute that can be ascribed to God, the Highest Being in the scale of Being. Man himself is divine in the rare moments when he attains to purely self-sufficient theoretical insight. In contrast with such knowing, the so-called knowing of the artisan is base. He has to bring about changes in things, in wood and stone, and this fact is of itself evidence that his material is deficient in Being. What condemns his knowledge even more is the fact that it is not disinterestedly for its own sake. It has reference to results to be attained, food, clothing, shelter, etc. It is concerned with things that perish, the body and its needs. It thus has an ulterior aim, and one which itself testifies to imperfection. For want, desire, affection of every sort, indicate lack. Where there is need and desire—as in the case of all practical knowledge and activity—there is incompleteness and insufficiency. While civic or political and moral knowledge rank higher than do the conceptions of the artisan, yet intrinsically considered they are a low and untrue type. Moral and political action is practical; that is, it implies needs and effort to satisfy them. It has an end beyond itself. Moreover, the very fact of association shows lack of self-sufficiency; it shows dependence upon others. Pure knowing is alone solitary, and capable of being carried on in complete, self-sufficing independence.
  • 57. In short, the measure of the worth of knowledge according to Aristotle, whose views are here summarized, is the degree in which it is purely contemplative. The highest degree is attained in knowing ultimate Ideal Being, pure Mind. This is Ideal, the Form of Forms, because it has no lacks, no needs, and experiences no change or variety. It has no desires because in it all desires are consummated. Since it is perfect Being, it is perfect Mind and perfect Bliss;—the acme of rationality and ideality. One point more and the argument is completed. The kind of knowing that concerns itself with this ultimate reality (which is also ultimate ideality) is philosophy. Philosophy is therefore the last and highest term in pure contemplation. Whatever may be said for any other kind of knowledge, philosophy is self-enclosed. It has nothing to do beyond itself; it has no aim or purpose or function—except to be philosophy —that is, pure, self-sufficing beholding of ultimate reality. There is of course such a thing as philosophic study which falls short of this perfection. Where there is learning, there is change and becoming. But the function of study and learning of philosophy is, as Plato put it, to convert the eye of the soul from dwelling contentedly upon the images of things, upon the inferior realities that are born and that decay, and to lead it to the intuition of supernal and eternal Being. Thus the mind of the knower is transformed. It becomes assimilated to what it knows. Through a variety of channels, especially Neo-Platonism and St. Augustine, these ideas found their way into Christian theology; and great scholastic thinkers taught that the end of man is to know True Being, that knowledge is contemplative, that True Being is pure Immaterial Mind, and to know it is Bliss and Salvation. While this knowledge cannot be achieved in this stage of life nor without supernatural aid, yet so far as it is accomplished it assimilates the human mind to the divine essence and so constitutes salvation. Through this taking over of the conception of knowledge as Contemplative into the dominant religion of Europe, multitudes were affected who were totally innocent of theoretical philosophy. There was bequeathed to generations of thinkers as an unquestioned
  • 58. axiom the idea that knowledge is intrinsically a mere beholding or viewing of reality—the spectator conception of knowledge. So deeply engrained was this idea that it prevailed for centuries after the actual progress of science had demonstrated that knowledge is power to transform the world, and centuries after the practice of effective knowledge had adopted the method of experimentation. Let us turn abruptly from this conception of the measure of true knowledge and the nature of true philosophy to the existing practice of knowledge. Nowadays if a man, say a physicist or chemist, wants to know something, the last thing he does is merely to contemplate. He does not look in however earnest and prolonged way upon the object expecting that thereby he will detect its fixed and characteristic form. He does not expect any amount of such aloof scrutiny to reveal to him any secrets. He proceeds to do something, to bring some energy to bear upon the substance to see how it reacts; he places it under unusual conditions in order to induce some change. While the astronomer cannot change the remote stars, even he no longer merely gazes. If he cannot change the stars themselves, he can at least by lens and prism change their light as it reaches the earth; he can lay traps for discovering changes which would otherwise escape notice. Instead of taking an antagonistic attitude toward change and denying it to the stars because of their divinity and perfection, he is on constant and alert watch to find some change through which he can form an inference as to the formation of stars and systems of stars. Change in short is no longer looked upon as a fall from grace, as a lapse from reality or a sign of imperfection of Being. Modern science no longer tries to find some fixed form or essence behind each process of change. Rather, the experimental method tries to break down apparent fixities and to induce changes. The form that remains unchanged to sense, the form of seed or tree, is regarded not as the key to knowledge of the thing, but as a wall, an obstruction to be broken down. Consequently the scientific man experiments with this and that agency applied to this and that condition until something begins to happen; until there is, as we say, something doing. He
  • 59. assumes that there is change going on all the time, that there is movement within each thing in seeming repose; and that since the process is veiled from perception the way to know it is to bring the thing into novel circumstances until change becomes evident. In short, the thing which is to be accepted and paid heed to is not what is originally given but that which emerges after the thing has been set under a great variety of circumstances in order to see how it behaves. Now this marks a much more general change in the human attitude than perhaps appears at first sight. It signifies nothing less than that the world or any part of it as it presents itself at a given time is accepted or acquiesced in only as material for change. It is accepted precisely as the carpenter, say, accepts things as he finds them. If he took them as things to be observed and noted for their own sake, he never would be a carpenter. He would observe, describe, record the structures, forms and changes which things exhibit to him, and leave the matter there. If perchance some of the changes going on should present him with a shelter, so much the better. But what makes the carpenter a builder is the fact that he notes things not just as objects in themselves, but with reference to what he wants to do to them and with them; to the end he has in mind. Fitness to effect certain special changes that he wishes to see accomplished is what concerns him in the wood and stones and iron which he observes. His attention is directed to the changes they undergo and the changes they make other things undergo so that he may select that combination of changes which will yield him his desired result. It is only by these processes of active manipulation of things in order to realize his purpose that he discovers what the properties of things are. If he foregoes his own purpose and in the name of a meek and humble subscription to things as they really are refuses to bend things as they are to his own purpose, he not only never achieves his purpose but he never learns what the things themselves are. They are what they can do and what can be done with them,— things that can be found by deliberate trying.
  • 60. The outcome of this idea of the right way to know is a profound modification in man's attitude toward the natural world. Under differing social conditions, the older or classic conception sometimes bred resignation and submission; sometimes contempt and desire to escape; sometimes, notably in the case of the Greeks, a keen esthetic curiosity which showed itself in acute noting of all the traits of given objects. In fact, the whole conception of knowledge as beholding and noting is fundamentally an idea connected with esthetic enjoyment and appreciation where the environment is beautiful and life is serene, and with esthetic repulsion and depreciation where life is troubled, nature morose and hard. But in the degree in which the active conception of knowledge prevails, and the environment is regarded as something that has to be changed in order to be truly known, men are imbued with courage, with what may almost be termed an aggressive attitude toward nature. The latter becomes plastic, something to be subjected to human uses. The moral disposition toward change is deeply modified. This loses its pathos, it ceases to be haunted with melancholy through suggesting only decay and loss. Change becomes significant of new possibilities and ends to be attained; it becomes prophetic of a better future. Change is associated with progress rather than with lapse and fall. Since changes are going on anyway, the great thing is to learn enough about them so that we be able to lay hold of them and turn them in the direction of our desires. Conditions and events are neither to be fled from nor passively acquiesced in; they are to be utilized and directed. They are either obstacles to our ends or else means for their accomplishment. In a profound sense knowing ceases to be contemplative and becomes practical. Unfortunately men, educated men, cultivated men in particular, are still so dominated by the older conception of an aloof and self- sufficing reason and knowledge that they refuse to perceive the import of this doctrine. They think they are sustaining the cause of impartial, thorough-going and disinterested reflection when they maintain the traditional philosophy of intellectualism—that is, of
  • 61. knowing as something self-sufficing and self-enclosed. But in truth, historic intellectualism, the spectator view of knowledge, is a purely compensatory doctrine which men of an intellectual turn have built up to console themselves for the actual and social impotency of the calling of thought to which they are devoted. Forbidden by conditions and held back by lack of courage from making their knowledge a factor in the determination of the course of events, they have sought a refuge of complacency in the notion that knowing is something too sublime to be contaminated by contact with things of change and practice. They have transformed knowing into a morally irresponsible estheticism. The true import of the doctrine of the operative or practical character of knowing, of intelligence, is objective. It means that the structures and objects which science and philosophy set up in contrast to the things and events of concrete daily experience do not constitute a realm apart in which rational contemplation may rest satisfied; it means that they represent the selected obstacles, material means and ideal methods of giving direction to that change which is bound to occur anyway. This change of human disposition toward the world does not mean that man ceases to have ideals, or ceases to be primarily a creature of the imagination. But it does signify a radical change in the character and function of the ideal realm which man shapes for himself. In the classic philosophy, the ideal world is essentially a haven in which man finds rest from the storms of life; it is an asylum in which he takes refuge from the troubles of existence with the calm assurance that it alone is supremely real. When the belief that knowledge is active and operative takes hold of men, the ideal realm is no longer something aloof and separate; it is rather that collection of imagined possibilities that stimulates men to new efforts and realizations. It still remains true that the troubles which men undergo are the forces that lead them to project pictures of a better state of things. But the picture of the better is shaped so that it may become an instrumentality of action, while in the classic view the Idea belongs ready-made in a noumenal world. Hence, it is only an
  • 62. object of personal aspiration or consolation, while to the modern, an idea is a suggestion of something to be done or of a way of doing. An illustration will, perhaps, make the difference clear. Distance is an obstacle, a source of trouble. It separates friends and prevents intercourse. It isolates, and makes contact and mutual understanding difficult. This state of affairs provokes discontent and restlessness; it excites the imagination to construct pictures of a state of things where human intercourse is not injuriously affected by space. Now there are two ways out. One way is to pass from a mere dream of some heavenly realm in which distance is abolished and by some magic all friends are in perpetual transparent communication, to pass, I say, from some idle castle-building to philosophic reflection. Space, distance, it will then be argued, is merely phenomenal; or, in a more modern version, subjective. It is not, metaphysically speaking, real. Hence the obstruction and trouble it gives is not after all real in the metaphysical sense of reality. Pure minds, pure spirits, do not live in a space world; for them distance is not. Their relationships in the true world are not in any way affected by special considerations. Their intercommunication is direct, fluent, unobstructed. Does the illustration involve a caricature of ways of philosophizing with which we are all familiar? But if it is not an absurd caricature, does it not suggest that much of what philosophies have taught about the ideal and noumenal or superiorly real world, is after all, only casting a dream into an elaborate dialectic form through the use of a speciously scientific terminology? Practically, the difficulty, the trouble, remains. Practically, however it may be metaphysically, space is still real:—it acts in a definite objectionable way. Again, man dreams of some better state of things. From troublesome fact he takes refuge in fantasy. But this time, the refuge does not remain a permanent and remote asylum. The idea becomes a standpoint from which to examine existing occurrences and to see if there is not among them something which gives a hint of how communication at a distance can be effected,
  • 63. something to be utilized as a medium of speech at long range. The suggestion or fancy though still ideal is treated as a possibility capable of realization in the concrete natural world, not as a superior reality apart from that world. As such, it becomes a platform from which to scrutinize natural events. Observed from the point of view of this possibility, things disclose properties hitherto undetected. In the light of these ascertainments, the idea of some agency for speech at a distance becomes less vague and floating: it takes on positive form. This action and reaction goes on. The possibility or idea is employed as a method for observing actual existence; and in the light of what is discovered the possibility takes on concrete existence. It becomes less of a mere idea, a fancy, a wished-for possibility, and more of an actual fact. Invention proceeds, and at last we have the telegraph, the telephone, first through wires, and then with no artificial medium. The concrete environment is transformed in the desired direction; it is idealized in fact and not merely in fancy. The ideal is realized through its own use as a tool or method of inspection, experimentation, selection and combination of concrete natural operations. Let us pause to take stock of results. The division of the world into two kinds of Being, one superior, accessible only to reason and ideal in nature, the other inferior, material, changeable, empirical, accessible to sense-observation, turns inevitably into the idea that knowledge is contemplative in nature. It assumes a contrast between theory and practice which was all to the disadvantage of the latter. But in the actual course of the development of science, a tremendous change has come about. When the practice of knowledge ceased to be dialectical and became experimental, knowing became preoccupied with changes and the test of knowledge became the ability to bring about certain changes. Knowing, for the experimental sciences, means a certain kind of intelligently conducted doing; it ceases to be contemplative and becomes in a true sense practical. Now this implies that philosophy, unless it is to undergo a complete break with the authorized spirit of science, must also alter its nature. It must assume a practical
  • 64. nature; it must become operative and experimental. And we have pointed out what an enormous change this transformation of philosophy entails in the two conceptions which have played the greatest rôle in historic philosophizing—the conceptions of the real and ideal respectively. The former ceases to be something ready- made and final; it becomes that which has to be accepted as the material of change, as the obstructions and the means of certain specific desired changes. The ideal and rational also ceased to be a separate ready-made world incapable of being used as a lever to transform the actual empirical world, a mere asylum from empirical deficiencies. They represent intelligently thought-out possibilities of the existent world which may be used as methods for making over and improving it. Philosophically speaking, this is the great difference involved in the change from knowledge and philosophy as contemplative to operative. The change does not mean the lowering in dignity of philosophy from a lofty plane to one of gross utilitarianism. It signifies that the prime function of philosophy is that of rationalizing the possibilities of experience, especially collective human experience. The scope of this change may be realized by considering how far we are from accomplishing it. In spite of inventions which enable men to use the energies of nature for their purposes, we are still far from habitually treating knowledge as the method of active control of nature and of experience. We tend to think of it after the model of a spectator viewing a finished picture rather than after that of the artist producing the painting. Thus there arise all the questions of epistemology with which the technical student of philosophy is so familiar, and which have made modern philosophy in especial so remote from the understanding of the everyday person and from the results and processes of science. For these questions all spring from the assumption of a merely beholding mind on one side and a foreign and remote object to be viewed and noted on the other. They ask how a mind and world, subject and object, so separate and independent can by any possibility come into such relationship to each other as to make true knowledge possible. If
  • 65. knowing were habitually conceived of as active and operative, after the analogy of experiment guided by hypothesis, or of invention guided by the imagination of some possibility, it is not too much to say that the first effect would be to emancipate philosophy from all the epistemological puzzles which now perplex it. For these all arise from a conception of the relation of mind and world, subject and object, in knowing, which assumes that to know is to seize upon what is already in existence. Modern philosophic thought has been so preoccupied with these puzzles of epistemology and the disputes between realist and idealist, between phenomenalist and absolutist, that many students are at a loss to know what would be left for philosophy if there were removed both the metaphysical task of distinguishing between the noumenal and phenomenal worlds and the epistemological task of telling how a separate subject can know an independent object. But would not the elimination of these traditional problems permit philosophy to devote itself to a more fruitful and more needed task? Would it not encourage philosophy to face the great social and moral defects and troubles from which humanity suffers, to concentrate its attention upon clearing up the causes and exact nature of these evils and upon developing a clear idea of better social possibilities; in short upon projecting an idea or ideal which, instead of expressing the notion of another world or some far-away unrealizable goal, would be used as a method of understanding and rectifying specific social ills? This is a vague statement. But note in the first place that such a conception of the proper province of philosophy where it is released from vain metaphysics and idle epistemology is in line with the origin of philosophy sketched in the first hour. And in the second place, note how contemporary society, the world over, is in need of more general and fundamental enlightenment and guidance than it now possesses. I have tried to show that a radical change of the conception of knowledge from contemplative to active is the inevitable result of the way in which inquiry and invention are now conducted. But in claiming this, it must also be conceded, or rather
  • 66. asserted, that so far the change has influenced for the most part only the more technical side of human life. The sciences have created new industrial arts. Man's physical command of natural energies has been indefinitely multiplied. There is control of the sources of material wealth and prosperity. What would once have been miracles are now daily performed with steam and coal and electricity and air, and with the human body. But there are few persons optimistic enough to declare that any similar command of the forces which control man's social and moral welfare has been achieved. Where is the moral progress that corresponds to our economic accomplishments? The latter is the direct fruit of the revolution that has been wrought in physical science. But where is there a corresponding human science and art? Not only has the improvement in the method of knowing remained so far mainly limited to technical and economic matters, but this progress has brought with it serious new moral disturbances. I need only cite the late war, the problem of capital and labor, the relation of economic classes, the fact that while the new science has achieved wonders in medicine and surgery, it has also produced and spread occasions for diseases and weaknesses. These considerations indicate to us how undeveloped are our politics, how crude and primitive our education, how passive and inert our morals. The causes remain which brought philosophy into existence as an attempt to find an intelligent substitute for blind custom and blind impulse as guides to life and conduct. The attempt has not been successfully accomplished. Is there not reason for believing that the release of philosophy from its burden of sterile metaphysics and sterile epistemology instead of depriving philosophy of problems and subject-matter would open a way to questions of the most perplexing and the most significant sort? Let me specify one problem quite directly suggested by certain points in this lecture. It has been pointed out that the really fruitful application of the contemplative idea was not in science but in the esthetic field. It is difficult to imagine any high development of the
  • 67. fine arts except where there is curious and loving interest in forms and motions of the world quite irrespective of any use to which they may be put. And it is not too much to say that every people that has attained a high esthetic development has been a people in which the contemplative attitude has flourished—as the Greek, the Hindoo, the medieval Christian. On the other hand, the scientific attitude that has actually proved itself in scientific progress is, as has been pointed out, a practical attitude. It takes forms as disguises for hidden processes. Its interest in change is in what it leads to, what can be done with it, to what use it can be put. While it has brought nature under control, there is something hard and aggressive in its attitude toward nature unfavorable to the esthetic enjoyment of the world. Surely there is no more significant question before the world than this question of the possibility and method of reconciliation of the attitudes of practical science and contemplative esthetic appreciation. Without the former, man will be the sport and victim of natural forces which he cannot use or control. Without the latter, mankind might become a race of economic monsters, restlessly driving hard bargains with nature and with one another, bored with leisure or capable of putting it to use only in ostentatious display and extravagant dissipation. Like other moral questions, this matter is social and even political. The western peoples advanced earlier on the path of experimental science and its applications in control of nature than the oriental. It is not, I suppose wholly fanciful, to believe that the latter have embodied in their habits of life more of the contemplative, esthetic and speculatively religious temper, and the former more of the scientific, industrial and practical. This difference and others which have grown up around it is one barrier to easy mutual understanding, and one source of misunderstanding. The philosophy which, then, makes a serious effort to comprehend these respective attitudes in their relation and due balance, could hardly fail to promote the capacity of peoples to profit by one another's experience and to co-operate more effectually with one another in the tasks of fruitful culture.
  • 68. Indeed, it is incredible that the question of the relation of the real and the ideal should ever have been thought to be a problem belonging distinctively to philosophy. The very fact that this most serious of all human issues has been taken possession of by philosophy is only another proof of the disasters that follow in the wake of regarding knowledge and intellect as something self- sufficient. Never have the real and the ideal been so clamorous, so self-assertive, as at the present time. And never in the history of the world have they been so far apart. The world war was carried on for purely ideal ends:—for humanity, justice and equal liberty for strong and weak alike. And it was carried on by realistic means of applied science, by high explosives, and bombing airplanes and blockading marvels of mechanism that reduced the world well nigh to ruin, so that the serious-minded are concerned for the perpetuity of those choice values we call civilization. The peace settlement is loudly proclaimed in the name of the ideals that stir man's deepest emotions, but with the most realistic attention to details of economic advantage distributed in proportion to physical power to create future disturbances. It is not surprising that some men are brought to regard all idealism as a mere smoke-screen behind which the search for material profit may be more effectually carried on, and are converted to the materialistic interpretation of history. Reality is then conceived as physical force and as sensations of power, profit and enjoyment; any politics that takes account of other factors, save as elements of clever propaganda and for control of those human beings who have not become realistically enlightened, is based on illusions. But others are equally sure that the real lesson of the war is that humanity took its first great wrong step when it entered upon a cultivation of physical science and an application of the fruits of science to the improvement of the instruments of life—industry and commerce. They will sigh for the return of the day when, while the great mass died as they were born in animal fashion, the few elect devoted themselves not to science and the material decencies and comforts of existence but to ideal things, the things of the spirit.
  • 69. Yet the most obvious conclusion would seem to be the impotency and the harmfulness of any and every ideal that is proclaimed wholesale and in the abstract, that is, as something in itself apart from the detailed concrete existences whose moving possibilities it embodies. The true moral would seem to lie in enforcing the tragedy of that idealism which believes in a spiritual world which exists in and by itself, and the tragic need for the most realistic study of forces and consequences, a study conducted in a more scientifically accurate and complete manner than that of the professed Real- politik. For it is not truly realistic or scientific to take short views, to sacrifice the future to immediate pressure, to ignore facts and forces that are disagreeable and to magnify the enduring quality of whatever falls in with immediate desire. It is false that the evils of the situation arise from absence of ideals; they spring from wrong ideals. And these wrong ideals have in turn their foundation in the absence in social matters of that methodic, systematic, impartial, critical, searching inquiry into real and operative conditions which we call science and which has brought man in the technical realm to the command of physical energies. Philosophy, let it be repeated, cannot solve the problem of the relation of the ideal and the real. That is the standing problem of life. But it can at least lighten the burden of humanity in dealing with the problem by emancipating mankind from the errors which philosophy has itself fostered—the existence of conditions which are real apart from their movement into something new and different, and the existence of ideals, spirit and reason independent of the possibilities of the material and physical. For as long as humanity is committed to this radically false bias, it will walk forward with blinded eyes and bound limbs. And philosophy can effect, if it will, something more than this negative task. It can make it easier for mankind to take the right steps in action by making it clear that a sympathetic and integral intelligence brought to bear upon the observation and understanding of concrete social events and forces, can form ideals, that is aims, which shall not be either illusions or mere emotional compensations.
  • 72. THE SIGNIFICANCE OF LOGICAL RECONSTRUCTION Logic—like philosophy itself—suffers from a curious oscillation. It is elevated into the supreme and legislative science only to fall into the trivial estate of keeper of such statements as A is A and the scholastic verses for the syllogistic rules. It claims power to state the laws of the ultimate structure of the universe, on the ground that it deals with the laws of thought which are the laws according to which Reason has formed the world. Then it limits its pretensions to laws of correct reasoning which is correct even though it leads to no matter of fact, or even to material falsity. It is regarded by the modern objective idealist as the adequate substitute for ancient ontological metaphysics; but others treat it as that branch of rhetoric which teaches proficiency in argumentation. For a time a superficial compromise equilibrium was maintained wherein the logic of formal demonstration which the Middle Ages extracted from Aristotle was supplemented by an inductive logic of discovery of truth that Mill extracted from the practice of scientific men. But students of German philosophy, of mathematics, and of psychology, no matter how much they attacked one another, have made common cause in attack upon the orthodox logics both of deductive proof and inductive discovery. Logical theory presents a scene of chaos. There is little agreement as to its subject-matter, scope or purpose. This disagreement is not formal or nominal but affects the treatment of every topic. Take such a rudimentary matter as the nature of judgment. Reputable authority can be quoted in behalf of every possible permutation of doctrine. Judgment is the central thing in logic; and judgment is not logical at all, but personal and psychological. If logical, it is the primary function to which both conception and inference are
  • 73. subordinate; and it is an after-product from them. The distinction of subject and predicate is necessary, and it is totally irrelevant; or again, though it is found in some cases, it is not of great importance. Among those who hold that the subject-predicate relationship is essential, some hold that judgment is an analysis of something prior into them, and others assert that it is a synthesis of them into something else. Some hold that reality is always the subject of judgment, and others that reality is logically irrelevant. Among those who deny that judgment is the attribution of predicate to subject, who regard it as a relation of elements, some hold that the relation is internal, some that it is external, and others that it is sometimes one and sometimes the other. Unless logic is a matter of some practical account, these contrarieties are so numerous, so extensive, and so irreconcilable that they are ludicrous. If logic is an affair of practical moment, then these inconsistencies are serious. They testify to some deep-lying cause of intellectual disagreement and incoherency. In fact, contemporary logical theory is the ground upon which all philosophical differences and disputes are gathered together and focussed. How does the modification in the traditional conception of the relation of experience and reason, the real and ideal affect logic? It affects, in the first place, the nature of logic itself. If thought or intelligence is the means of intentional reconstruction of experience, then logic, as an account of the procedure of thought, is not purely formal. It is not confined to laws of formally correct reasoning apart from truth of subject-matter. Neither, on the contrary, is it concerned with the inherent thought structures of the universe, as Hegel's logic would have it; nor with the successive approaches of human thought to this objective thought structure as the logic of Lotze, Bosanquet, and other epistemological logicians would have it. If thinking is the way in which deliberate reorganization of experience is secured, then logic is such a clarified and systematized formulation of the procedures of thinking as will enable the desired reconstruction to go on more economically and efficiently. In language familiar to students, logic is both a science and an art; a science so far as it
  • 74. gives an organized and tested descriptive account of the way in which thought actually goes on; an art, so far as on the basis of this description it projects methods by which future thinking shall take advantage of the operations that lead to success and avoid those which result in failure. Thus is answered the dispute whether logic is empirical or normative, psychological or regulative. It is both. Logic is based on a definite and executive supply of empirical material. Men have been thinking for ages. They have observed, inferred, and reasoned in all sorts of ways and to all kinds of results. Anthropology, the study of the origin of myth, legend and cult; linguistics and grammar; rhetoric and former logical compositions all tell us how men have thought and what have been the purposes and consequences of different kinds of thinking. Psychology, experimental and pathological, makes important contributions to our knowledge of how thinking goes on and to what effect. Especially does the record of the growth of the various sciences afford instruction in those concrete ways of inquiry and testing which have led men astray and which have proved efficacious. Each science from mathematics to history exhibits typical fallacious methods and typical efficacious methods in special subject- matters. Logical theory has thus a large, almost inexhaustible field of empirical study. The conventional statement that experience only tells us how men have thought or do think, while logic is concerned with norms, with how men should think, is ludicrously inept. Some sorts of thinking are shown by experience to have got nowhere, or worse than nowhere—into systematized delusion and mistake. Others have proved in manifest experience that they lead to fruitful and enduring discoveries. It is precisely in experience that the different consequences of different methods of investigation and ratiocination are convincingly shown. The parrot-like repetition of the distinction between an empirical description of what is and a normative account of what should be merely neglects the most striking fact about thinking as it empirically is—namely, its flagrant exhibition of cases of failure and success—that is, of good thinking and bad thinking.
  • 75. Any one who considers this empirical manifestation will not complain of lack of material from which to construct a regulative art. The more study that is given to empirical records of actual thought, the more apparent becomes the connection between the specific features of thinking which have produced failure and success. Out of this relationship of cause and effect as it is empirically ascertained grow the norms and regulations of an art of thinking. Mathematics is often cited as an example of purely normative thinking dependent upon a priori canons and supra-empirical material. But it is hard to see how the student who approaches the matter historically can avoid the conclusion that the status of mathematics is as empirical as that of metallurgy. Men began with counting and measuring things just as they began with pounding and burning them. One thing, as common speech profoundly has it, led to another. Certain ways were successful—not merely in the immediately practical sense, but in the sense of being interesting, of arousing attention, of exciting attempts at improvement. The present-day mathematical logician may present the structure of mathematics as if it had sprung all at once from the brain of a Zeus whose anatomy is that of pure logic. But, nevertheless, this very structure is a product of long historic growth, in which all kinds of experiments have been tried, in which some men have struck out in this direction and some in that, and in which some exercises and operations have resulted in confusion and others in triumphant clarifications and fruitful growths; a history in which matter and methods have been constantly selected and worked over on the basis of empirical success and failure. The structure of alleged normative a priori mathematics is in truth the crowned result of ages of toilsome experience. The metallurgist who should write on the most highly developed method of dealing with ores would not, in truth, proceed any differently. He too selects, refines, and organizes the methods which in the past have been found to yield the maximum of achievement. Logic is a matter of profound human importance precisely because it is empirically founded and experimentally applied. So considered, the problem of
  • 76. logical theory is none other than the problem of the possibility of the development and employment of intelligent method in inquiries concerned with deliberate reconstruction of experience. And it is only saying again in more specific form what has been said in general form to add that while such a logic has been developed in respect to mathematics and physical science, intelligent method, logic, is still far to seek in moral and political affairs. Assuming, accordingly, this idea of logic without argument, let us proceed to discuss some of its chief features. First, light is thrown by the origin of thinking upon a logic which shall be a method of intelligent guidance of experience. In line with what has already been said about experience being a matter primarily of behavior, a sensori-motor matter, is the fact that thinking takes its departure from specific conflicts in experience that occasion perplexity and trouble. Men do not, in their natural estate, think when they have no troubles to cope with, no difficulties to overcome. A life of ease, of success without effort, would be a thoughtless life, and so also would a life of ready omnipotence. Beings who think are beings whose life is so hemmed in and constricted that they cannot directly carry through a course of action to victorious consummation. Men also do not tend to think when their action, when they are amid difficulties, is dictated to them by authority. Soldiers have difficulties and restrictions in plenty, but qua soldiers (as Aristotle would say) they are not notorious for being thinkers. Thinking is done for them, higher up. The same is too true of most workingmen under present economic conditions. Difficulties occasion thinking only when thinking is the imperative or urgent way out, only when it is the indicated road to a solution. Wherever external authority reigns, thinking is suspected and obnoxious. Thinking, however, is not the only way in which a personal solution of difficulties is sought. As we have seen, dreams, reveries, emotional idealizations are roads which are taken to escape the strain of perplexity and conflict. According to modern psychology, many systematized delusions and mental disorders, probably hysteria itself, originate as devices for getting freedom from
  • 77. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com