Home
Introduction to Fortran 90 for Scientists and Engineers
Contents
1. PRESENT A TRUE ifthe actual argument corresponding tothe dummy argument A is present in the currert call to a subprogram ASSOCIATED POINTER TARGET If TARGET is absent result is TRUE if POINTER is associated with a target FALSE otherwise The status of POINTER must n be undefined If TARGET is present result is TRUE if POINTER is associated with it If TARGET itselfis a pointer its target is compared with the target of POINTER and FALSE is rtumed if either POINTER or TARGET is disassociated PRESENT A TRUE ifthe actual argument corresponding tothe dummy argument A is present in the currert call to a subprogram C 11 Elemental Logical Function 271 LOGICAL L KIND function converts between kinds of logical value Returns the value of logical L with a kind parameter value of KIND if it is presert If scalar initialization expression C 12 Functions Relating to Kind KIND X kind parameter value of X SELECTED INT KIND R kind parameter value for an integer R R 10 lt n lt 10 KIND is present t must be a datatype able to represert all irteger values n inthe rang where R is ascalarirteger 1 is returnedif no such kind is available SELECTED R
2. Disc B B 4 A C Outer IF A 0 THEN Inner IF Disc lt 0 THEN PRINT Complex roots ELSE Inner X1 B SQRT Disc X2 B SQRT Disc END IF Inner END IF Outer What will happen ifthe END IF Inner is moved up 3 lines as shown below Outer IF A 0 THEN Inner IF Disc lt 0 THEN PRINT Complex roots END IF Inner Wrong place now ELSE Inner X1 B SQRT Disc 2 A X2 B SQRT Disc 2 A END IF Outer Well the compiler will object because of a clash of names ELSE Inner cannot appear after END IF Inner closs the Inner IF However if all the names are omitted the segment will compile but will make a division by zero certain if a 0 sin the ELSE will now belong to the first F try it Nesting may extendto any depth indentation and or naming should be carefully used in such cases to make the logic clearer DOs and IFs A DO loop may contain an IF construct and vice versa The basic rule isthat if a construct begins inside another construct it must also end inside that construct The following is therefore illegal DO I 1 10 IF I gt 5 THEN END DO Illegal IF must end before DO ND IF a and so is this IF THEN DO I 1 10 END IF Illegal DO must end before IF ND DO m
3. The program below implementsthis model Notethattwo sets of variables are used to represent th age groups C Y T and W represent values in year k while NC NY NT and NW represert values in year k 1 One might have been tempted to code the update equations as follows Y B C T yY G L D Y Y T W This however would mean that we would be using next year s Y obtained from equation 6 3 on the righthand side of equation 6 4 instead of this year s Usingt wo sets of variables means thatthe set representing the currert year s values must be updated at the end of each year in readiness for next year s update Try the program out with different parameter values to see what happens Also try running it for longer IMPLICIT NONE 74 INTEGER Year REAL A 0 45 adult birth rate REAL Ad 0 15 a dash 2 yr old birth rate REAL C 3660 calves REAL T 1680 2 yr olds REAL Tot total population REAL W 6440 adults REAL Y 2240 yearlings REAL NC NT NW NY next year s population REAL L D B G other model parameters DO Year 1969 1974 WRITE 14 data ADVANCE NO Year READ L D B G NY B C NT Y G L D Y T W NW W T G L D T W Y T W NC A NW Ad NT C NC Y NY T NT W NW Tot CG HTF Ww
4. Consider again the external subroutine SWOP X Y of Sectio 8 3 t accepts only real arguments We can make it accept irteger arguments as well ina number of ways One isto writet wo separate external subroutines SwopReals and SwopIntegers with real and irteger arguments respectively e g SUBROUTINE SwopReals X Y REAL X Y Temp Temp X XS Y Y Temp T END SUBROUTINE SwopReals and SUBROUTINE SwopIntegers X Y INTEGER X Y Temp Temp X xX Y Y Temp END SUBROUTINE SwopiIntegers 101 Since these are to be external subprograms each must reside in a separate file and be compiled separetely The overloading can then be done inthe main program by means of an INTERFACE statement which specifies the generic name SWOP and interface bodies for the two overloaded subroutines PROGRAM Main INTERFACE SWOP SUBROUTINE SwopReals X Y EAL X Y Temp SUBROUTINE SwopReals UTINE SwopIntegers X Y EGER X Y Temp UBROUTINE SwopIntegers ERFACE R END SUBR I D I zd Hunio gal Z OME Zz KH Q v5 H Q Q D nN O o H oD Q D n O g A specific name may be the same as the generic name ifthis is more conveniert A generic name may bethe same as ancther acces
5. Parts of the CASE constructmay be named inthe same way asthe IF construct The selection of grades in the amended Final Mark program of Section 5 1 can also be programmed with CASE ifthe mark Final is converted to integer type SELECT CASE INT Final CASE 75 PRINT Name CRM ExmAvg Final 1 Firsts Firsts 1 CASE 70 74 PRINT Name CRM ExmAvg Final 2 UpSeconds UpSeconds 1 CASE 60 69 54 PRINT Name CRM ExmAvg Final 2 LowSeconds LowSeconds 1 CASE 50 59 PRINT Name CRM ExmAvg Final 3 Thirds Thirds 1 CASE DEFAULT PRINT Name CRM ExmAvg Final F Fails Fails 1 END SELECT EAI T There aretimes when CASE is more efficient than IF since only one expression expr needs to be evaluated 5 4 The GO TO Statement TE would be difficult to overestimate the damage done to languages like Fortran and Basic by the indiscriminate and thoughtless use of the GOTO statement Proponerts of the classically more structured languages like Pascal and C regardit asthe programmer s four letter word I once heard a particularly caustic critic ask why Fortran didn t have a COME FROM statement GO TO isan unconditional branch and has the form GO TO label where label is a statement label a number in the range 1 99999 preceding a statement on the sam line Control passes unco
6. Some purists might argue that the EXIT should always be at the top of such a non deterministic loop sothat it is clearto a reader how a loop willend when she first encounters it The while do construct of languages like Pascal lends itself more readilytothis convention The way Fortran 90 is designed makes it more naturalto put the EXIT atthe end However Iam sure you are old enough to decide for yourself There is one situation in which the EXIT must be at thetop of the loop andthisis when a zero trip count is logically possible An example isthe original form of the guessing game above ifthe user guesses the number correctly first time there should be no executions of the DO block DO WHILE A DO construct may be headed witha DO WHILE statement DO WHILE logical expr block END DO This is logically equivalent to DO IF NOT logical expr EXIT block END DO The DO WHILE isa very compelling construction since the condition to repeat is stated clearly at the top of the loop t may however involve optimizatim penalties under certain circumstances There are many examples of its usage later 67 DO variations which are not recommended The EXIT statement may also be usedin aDO construct with a DO variable and parameters DO I 1 N IF I J EXIT ND DO
7. 14 6 Two players A and B playa game called Fights They simulation game of eightstake it in turns to choose a number 1 2 or 3 which may not be the same as the last number chosen so if A starts with 2 B may only choose 1 or 3 atthe next move A starts and may choose any of the three numbers for the firt move After each move the number chosen is added to a common running total Ifthetctal reaches 8 exactly the player whoseturn itwas winsthe game If a player causes the tctal to go over 8 the her player wins Forexample suppose A starts with 1 tctal 1 B chooses 2 t al 3 A chooses 1 tctal 4 and B chooses 2 tctal 6 A wouldliketo play 2 now to win but he can t because B cunningly played it on the last move so A chooses 1 tctal 7 This is even smarter because B is forced to play 2 or 3 making the tctal go over 8 and thereby losing Write a program to simulate each player s chances of winning ifthey always play amp random 196 Chapter 15 Matrices and Their Applications Chapter 15 Introduction 15 1 Tables a Concrete Example 15 2 Graphs Without Graphics 15 3 Matrices e Matrix multiplication e Defined operations for matrix handling 15 4 Array Handling Features e Array expressions e Array ions e Some more irtrinsic functions 15 5 Networks e A spy ring e The reachability matrix 15 6 Leslie Matrices
8. T e Every independent evert being simulated requires a separate random number Chapter 14 Exercises 14 1 Inagame of Bingothe numbers 1 to 99 are drawn at random fra a bag Writea programto simulate the draw of the numbers each number can be drawn only once pirting them ten to a lire 14 2 One dimensional random walk A gas molecule is constrained to move along the x axis Ik starts at the origin t moves randomly a large number of times to the left or night with equal probability one unit at atime Let the frequency F X bethe number of times it is at position X Write a program to compute these fi ncies and to print a bar chart representing them Assume that the molecule never moves outside the range Xmax to Xmax 14 3 RANDOM NUMBER can be usedto estimate T as follows such a method is calleda Monte Carlo method Write a program which generates random poirts in a square of length 2 say and which counts what proportion of these points fallsinsidethe circle of unit radius that fits exactly into the square This proportion will be the ratio of the area of the circle to that of the square Hence estimate m Thisis not a very efficiert method as you will see from the number of points required to get even a rough approximation 14 4 The aim of this exercise isto simulate bacteria growth Suppose that a certain type
9. Ifthe named constart is of charactertype its length may be declared with an asterisk The actual length is then determined by the compiler saving you the bother of counting all the characters E g CHARACTER LEN PARAMETER amp Message Press ENTER to continue LEN character constantcharacter constant LEN 31 3 5 Kind The concept of kind is a new feature of Fortran 90 with which experienced Fortran programmers will need to get to grips Each of the five intrinsic types has a default kind this is required by the standard There may be a number of other kinds these will be system dependent and are not specified by the standard Associated with each kind is a non negative integer called the kind type parameter The value of the kind parameter enables you to identify the various kinds available Integer kinds For example the FTN90 compiler supportsthree irteger kinds on a PC The default kind has a kind 31 31 parameter value of 3 and represents integers inthe rang r 2n eN There are a number of irtrinsic functions which enable you to establish kind related properties and more importantly to specify a kind which will suit your precision requirements Irteger constants automatically have default kind that is what the word default means The function KIND I KIND returns the value of the kind parameter of its argument re
10. The PARAMETER attribute is one of many that may be specified in a type declaration statement Further attributes will be introduced later Named constants may themselves be used when initializing The expression thus formed is an initialization expression initialization expressions are in fact special cases of constant expressions which may appear in cther contexts E g REAL PARAMETER Pi 3 141593 INTEGER PARAMETER Two 2 REAL PARAMETER OneOver2Pi 1 2 Pi REAL PARAMETER PiSquared Pi Two Since initialization expressions are evaluated at compile time there are certain restrictions on their form At this dage the relevant ones are e they may only involve irtrinsic operators e the exponentiation operator must have an irteger power e irtrinsic functions must have irteger or character arguments and results The following istherefore not allowed given the definition of Pi above REAL PARAMETER OneOverRoot2Pi 1 SORT 2 Pi In general a double colon must appear wherever an attribute is specified or an initialization expression is used otherwise itis optional Ifthe PARAMETER attribute is specified an initialization expression must appear
11. BLANK char NULL default ZERO sets default for interpretation of blanks as nulls or zeros formatted records only POSITION char ASIS default file is opened at previous positim REWIND opened at initial position APPEND opened ahead of endfile record sequential access only 7 ACTION char READ read only WRITE write only READWRITE both default is system dependent JZ ELIM char APOSTROPHE QUOTE NONE default indicates delimiter character used for character constants with lisdirected or NAME LIST formatting PAD char YES default formatted input record regarded as padded with blanks if inout list and associated format specify more data than appear in record NO OPEN 2 FILI Gl Students ACCESS DIRECT amp STATUS OLD RECL 40 OPTIONAL specifiesthe OPTIONAL attribute for dummy arguments See REAL iesthe PARAMETER attribute to name a constark See REAL PARAMETER speci PAUSI Gl obsolescent and not recommended suspends execution pending external irtervention POINTER specifies the POINTER attribute eg REAL POINTER P REAL TARGET R P gt R P is an alias for its target R TE may also be used to allocate dynamic storage
12. REAL DIMENSION A R REAL DIMENSION SIZE A 1 SIZE A 2 B B A R A N SIZE A 1 DO I 1 N 2 B B x A R R B END DO D SUBROUTINE Reachable wo Zz END PROGRAM Reach automatic object TE may help to go through Reachable by hand for n 5 to see how it works Keep track of the contents of B and R interms of the adjacency matrix A 15 6 Leslie Matrices Population Growth Ancther very interesting and useful application of matrices is in population dynamics The rabbit population model of Chapter 10 can be made a lct more realistic if we allow some rabbits to die from time totme The approach we are going to take requires that we divide the rabbit population up irto a number of age classes where the me mbers of each age class are one time unit olderthan the members of the previous class the time unit being whatever is conveniert for the population being studied days months etc If x isthe size of the ith age class we define a survival factor F as the proportion of the th class that survive tothe i 1 th age class i e the proportion that graduate F is defined asthe mean fertility of the ith class Thisisthe mean number of newborn individuals expected to be produced during one time interval by each member of the th class at the beginning of the irterval only females count in biological modelling
13. CALL PLUNK A B C 99 would generete a compiler eror B is an expression n a variable Tf the irtert is INOUT the corresponding actual argument must again be a variable Ifthe dummy argument has no irtert the actual argument may be a variable or an expression E is recommended that all dummy arguments be given an irtert In particular all function arguments should have irtert IN Irtent may also be specified in a separate statement eg INTENT INOUT X Y Z Matching type The type of an actual argument must match the type of the corresponding dummy argument E PLONK is fined with one real argument the statement Pl Q E CALL PLONK 0 will cause an error because the constart 0 is an irteger Optional and keyword arguments Argument listtscan get very long sometimes not all of tham are needed Some or all ofthe dummy arguments may be specified withthe OPTIONAL attribute which may also be used as a statement Ifthe wanted arguments happen to be consecutive starting from the firs dummy argument they are listed normallyinthe CALL statement However the wanted arguments may be scattered in which case a keyword argument list must be provided after an ordinary positional argument lit which may be empty Perhaps an example will clarify the situation The external subroutine Plonk has six arguments the last four of whi
14. Gl END F a PROGRAM MONEY We will now discuss in detail how the program works When you run a Fortran 90 program two separate processes take place Firstly the program is compiled This means that each statement is translated into some sort of machine code thatthe computer can understand Secondly the compiled program is executed Inthis step each translated instruction is camied out The soft ware package that carries out both these processes is generally called a compiler During compilation space inthe computer s random access memory RAM is allocated for any numbers data which willbe genereted by the program This part ofthe memory may bethought of as a bank of boxes or memory locations each of which can hold only one number at atime These memory 1 jons are referred to by symbolic names inthe program So the statement F ANCE BA 1000 Pie allocates BA location named BALANCI called a variable the number 1000 to the memory Since the contents of E may change during the program itis translated compiled fom of our program 1 ANCE The ks roughly as follows F ANCE T F E t tl BA Put the number 0 09 irto memory location RAT Multiply the conterts of RATE by the cortents of BALANCE and put the answer in INTEREST Add the contents of BALANCE tothe cortents of INTEREST and put the answer in BALANCI Print disp
15. Tf an intrinsictoken is used the number of arguments and priority isthe same as forthe irtrinsic operation Otherwise defined unary inary operators have the highest lowest priority An operation that is defined on intrinsic types cannot be redef operation X scalar product You must either use a di ined For example since thr Y is defined intrinsically for arrays the operator cannot be redefined as a fferent token or def ine a new type e Inthisexample the set isimplemented as a fixed length array t could however just as easily be reoreserted by a linked lig which would n require the module to be recompiled 157 Structure valued functions Note incidentally from the previous example that a function may be structure valued i e it may return the value of a derived type We will see further examples of derived types assignment and operator overloading and structure and array valued functions in Chapter 15 The TYPE statement The general form of a derived type definition is TYPE access typename PRIVATE component definitions END TYPE typename By default atype and all its components are accessible PUBLIC access The access qualifier PRIVATE orthe PRIVATE statement may only appear ifthetype is defined in a module Ifthetype is specifiedas PRIVATE then b
16. iles usuallyis a few names init which you can s amp up with your text editor The original file is then deleted a new empty file of the same name is leis copied back Ik sounds cumbersame because Try the program out on a text file with CHARACTER 80 Name FileName Ans WRITE A ADVANCE NO Name of file to be updated READ FileName OPEN 1 FILE FileName OPEN 2 STATUS SCRATCH IO 0 DO WHILE IO 0 READ 1 IOSTAT IO Name IF IO 0 THEN PRINT Name WRITE A ADVANCE NO Delete Y N READ Ans could be upper or lowercase IF Ans Y AND Ans y WRITE 2 Name END IF END DO REWIND 2 back to the beginning of SCRATCH CLOSE 1 STATUS DELETE delete original OPEN 1 FILE FileName recreate original IO 0 DO WHILE IO 0 READ 2 IOSTAT IO Name 134 L IF IO 0 WRIT END DO CLOSE 1 CLOSE 2 END Notethatthetwo DO WHIL past the end of the file The OPEN statement has the OPEN UNIT Ju speclis Gl Name keep delete E loops make use ofthe IOSTAT specifierto avoid an attempted READ form t where u isthe file unit number and speclist is a list of specifiers many of which are optional and
17. is created if it does not exist if it does exist itis deleted and a new file is created withthe same name The simple form of the OPEN statement used in the program above connects a file for sequential access the default mode of access with formatted records the default for sequential access These properties may be changed by the ACCESS and FORM specifiers as we shall see below APPEND New data may be written at the end of a sequential file by setting the POSITION specifier to Errors e g attempting to open a non existert file with status OLD may be intercepted with the IOSTAT and ERR specifiers This avoids a crash you can program a more graceful response A sequential file may be repositioned to its initial poirt with the statement REWIND u The statement BACKS PACE u positions a sequential file before the current record if it is positioned within a record or before the preceding record if it is positi ned between records This statement is costly in computer overheads and should be avoided The end of a sequential fil is marked by a special record called the endfile record Most computer systems will automatically writethis record at the end of a sequential file However if you are in
18. and above if necessary the pivot element Take the target row R Replace each element in th row by itself minus the conesponding element inthe pivct row The array now looks like this 1 1 2 1 2 2 0 3 2 1 2 ied 3 1 1 1 Now take the target row R To reduce 31 to zero with an operation involving the pivot row a3 requires replacing the target row by itself minus the pivct row multiplied by bearing in mind forthe subsequent computer solution that this operation can change the value of a3 self 1 1 2 1 2 2 0 3 2 1 2 1 0 1 2 5 2 5 We now designat R as the piv row and the new a 2 as th piv element The whol procedure is repeated except that the target rows are now R and R andthe object isto get zeros inthese two rows above and below the pivot element The result is 1 0 2 3 7 3 0 1l 1 3 2 3 0 0 8 3 16 3 Now take R as the pivot row withthe new a33 as the piv element and R and R as targ amp rows After repeating similar operations on them the array finally looks like this 1 0 0 1 0 0 Oo e l 0 2 Since we have retained the mathematical integrity of the system of equations by performing operations on the rows only this is equivalent to x Oy Oz 1 Ox H y Oz 0 Ox Oy z 2 The solution may therefore be read off as x 1 y 0 7 2 The subroutine G
19. every dt seconds These times ae most unlikely to be irtegers 62 One way to solvethis problem isto calculate our own iteration count forthe problem The number of irtervals involved is 1 E to dt Since we wart the result at each end of the interval bet ween t 9 and fi we need to add 1 tothis The obvious value for our iteration count is therefore f t5 ot 4 Now since this must be an integer do we truncate it with INT or round it with NINT To answer this we must first decide what must happen if tbo is not an exact multiple of dt Let s say we don t want calculations made outside our specified range That rules out NINT Suppose fo 0 P hs 5 and dt 0 4 Our iteration court is 12 5 exactly Rounding up with NINT would give 13 with an unwanted cal ion beyond t So INT must be used However this also has its problems Because of rounding error the number of irtervals t 4 fat could easily just fall short of a whole number like 10 0 1 coming out as 99 9999 instead of 100 so truncating would lose one loop Fortran 90 has a neat solution to this problem The new intrinsic function SPACING X returns the absolute spacing between SPACING values near X So the most satisfactory answer is to add SPACING dt to the iteration count before truncating The following program reads values for to TStart fi TEnd and dt and
20. statement 10 while RETURN 2 returmsto statement 30 REWIND 3 REWIND 2 SAVE specifies the SAV retain their currert values between cal IOSTAT REWIND repositions a sequent E ath ial file at its initial poirt The syrtax isthe same as for backspace eg IO ribute for local variables declared in subprograms i e such variables ls See REAL All variables which have been initialized acquire the SAVE attribute automatically SELECT CASI definitions in diff E See CASI Gl SEQUENCE not recommended specifies the SEQUENCE attribute for derived types Two type fert scoping units define the same datatype if they have the same name and componerts and if both have the SEQU association tis betterto have a single definition in a module accessible to bcth scoping units STOP not recommended stops program their programs at places cther than at the I SUBROUTINE RECURSIV Gl If there are no arguments ENCE attribute giving them what is called storage names a subroutine execution This is needed by people who want to stop END SUBROUTINE NAME A B C ldots END SUBROUTIN T NAME SUBROUTINE NONE F Statements T
21. INTEGER NFACT 1 INTEGER N REAL XFACT 1 DO N 1 20 NFACT NFACT N XFACT XFACT N PRINT N NFACT XFACT END DO Binomial coefficient Thisis widely used in istics The number of ways of choosing r objects out of n without regardto order is given by es 10 10x9x8 e g n n n 1 n 2 n r 1 r ri n r r 3 3 x7 1x2x3 Ifthe form involving factorialsis used the numbers can get very big causing the cycling problem shown in the previous example But using the right most expression above is much more efficiert gt INTEGER BIN 1 INTEGER K N R PRINT Give values for N and R READ N R DO K 1 R BIN BIN N K 1 K END DO PRINT N c R BIN Limit of a sequence DO loops are ideal for computing successive members of a sequence Thisexample also highlights a problem that sometimes occurs when computing a limit Consider the sequence x a n n 1 2 3 n where a is any constant and n isthe factorial function defined above The question is what is the limit of this sequence as n gets indefinitely large Let stakethe case a 10 If wetrytocompute Xn directly we could get into trouble because n gets large very rapidly as n increases and cycling or 59 overflow could occur However the situation
22. may be in any order The unit number must appear first unless it is specified with UNIT The specifiers are character expressions or constarts If character expressions are used trailing blanks are ignored Except forthe FILE specifier lowercase letters are converted to uppercase You also need to know that the OPEN statement can be executed on a unit number which is already connected to a file This is to enable the properties of a connection to be changed and is only allowed with certain specifiers for example the BLANK specifier which sets the default for the irterpretation of blanks to nulls or zeros Some of the more common the gory cetails The FILE specifier is a character expression which givesthe name of th specifiers are described below you should consult Appendix B for all le If this specifier is omitted and the unit is not already connected the STATUS specifier must appear with the value SCRATCH If SCRATCH is speci ied forthe STATUS specifier as above on unit 2 atemporary file is created TE ceases to exist when the unit is closed or when the program terminates If NEW is specified the file must nct already exist IF OLD is specified it must already exist If REPLACE is specified the fil
23. seeds the random number generator 65 IF MyGuess gt FtnNum THEN PRINT Too high Try again H iS B PRINT Too low Try again END IF WRITE Your guess ADVANC READ MyGuess END DO PRINT BINGO Well done z ll E NO CALL RANDOM_SEED GET Seed get th PRINT PRINT New seed Seed 1 new seed for another game Try it out a few times Note that the DO loop which now has no variables or parameters repeats as long as MyGuess is nc equal to FtnNum There is no way of knowing in principle how many loops will be needed before they are equal and so this new form of the DO construct is essential here In this case looping terminates when the statement nom deterministic On reflection you might feel the coding is a little wasteful WRITE Your guess ADVANCE READ MyGuess EXIT is executed The problem is truly The section NO has to appeartwice Once to start the loop going or MyGuess would be undefined and a second with changes is reproduced FtnNum INT 10 R 1 remove two lines DO WRITE Your guess ADVANC READ MyGuess IF MyGuess gt FtnNum THEN PRINT Too high Try again ELSE IF MyGuess lt FtnNum THEN PRINT Too low Try again B iS H PRINT Well done END IF IF MyGuess FtnNum
24. DO WHILE repeats a block of statements conditionally DO WHILE ABS F X gt 1E 6 m z D DO Metcalf and Reid warn that DO WHILE may be inefficiert when execution time is a critical factor Since most examples inthis book do not fall inthis category I have used it in preference to DO with EXIT t makes the logic much clearer DOUBLE PRECISION not recommended specifies a real variable with a precision higher than the default DOUBLE PRECISION X TE is the Fortran 77 user s cop out for not learning about kind type parameters which are discussed fully in Chapter 3 Statements E through F END isthe final tatement in a program unit or subprogram ENDFILE writes an endfile record to a sequential file In general ENDFILE UNIT u IOSTAT io ERR label The specifiers have the same meaning as inOPEN ENTRY not recommended allows a subprogram to be entered at poirts cther than at the beginning and therefore defeats the purpose of writing subprograms as logical units SUBROUTINE JUNK dummy arglist T ENTRY SILLY dummy arglist ENTRY WORSE dummy arglist END SUBROUTINE You canthen call JUNK SILLY or even WORSE depending on exactly where you would liketo start
25. EQUIVALENCE not recommended enablest wo or more objects inthe same program unit to share the same storage area E g 252 EQUIVALENCE A B X Y allows A and B onthe one hand and X and Y on the other to sharethe same storage area Since y array elements occupy consecutive storage locations you can get some really weird results E g INTEGER A 2 B 3 X 2 2 EQUIVALENCE A 2 B 1 X 1 2 implements the following arrangement elements inthe same column share storage A 1 A 2 B 1 B 2 B 3 X 1 1 X 2 1 X 1 2 X 2 2 Tf you wart to use different names forthe same object st up an alias with a poirter EXIT conditionally recommended allows exit from a DO construct see example under DO You should exit fran as closetothetop or botan of a DO as possiblein orderto make the exit condition easy to see Multiple exits are definitely not recommended EXTERNAL specifies each name listed as the name of an external or dummy procedure The irterface remains implicit If an explicit interface is needed use an INTERFACE block this is generally recon mended E g EXTERNAL F FORMAT provides an I O format specification It is described fully in Chapter 10 See PRINT for examples FUNCTION names a function subprogram FUNCTION Factoria
26. Zz iw J O RINT 10I3 Bing D m u ii Z 14 2 ROGRAM Walk EGER PARAMETER Xmax 20 EGER X F Xmax Xmax I N LR T T N N AHH g D 284 X 0 F 0 READ N DO I 1 N CALL RANDOM NUMBER R IF R lt 0 5 THEN X 1 Il W aZ xOKN XK IF o Hj m DO X Xmax Xmax PRINT 80A1 I 1 F X DO o Fl O m 22a 14 3 PROGRAM MonteCarlo FAL Ry Xy Y Pi ER I N 0 AD N DO I 1 N CALL RANDOM_NUMBER R D UHD 2 E H Q AP X 1 2 R sed porch Yoel 2 CR ditto IF X X Y Y lt 1 Pi Pi 1 END DO Pi 4 Pi N PRINT Pi is very roughly Pi END F X 1 that s another one at X 14 5 Theoretically from the binomial distribution the probability of a DFII crashing is 1 4 while that of a DFTV crashing is 5 16 more can go wrong with it since it has more engines 14 6 On average A wins 12 of the possible 32 plays of the game while B wins 20 as can be seen from drawing the game tree Your simulation should come up with these proportions However it can be shown from the tree that B can always force a win if she plays irtellicertly Chapter 15 151 SUBROUTINE MyTrans A REAL DIMENSION A INTEGER J K REAL Temp DO J 1 SIZE A 1 DO K J SIZE A 1 start at J to avoid swoppi
27. it from the loop 75 The syntax of these forms is DO IF condition EXIT block END DO IF condition EXIT END DO A non deterministic loop may also be programmed witha DO WHILE construct Here the general structure plan is While condition is true repeat Block of statements to be repeated Note that condition is now the condition tomake ancther iteration not to exit The syntax for this structure is DO WHILE condition block END DO This construct may incur o timi zation penalties The DO variable and parameters should be irtegers The DO variable should n be explicitly changed inthe DO block The iteretion count which may be zero is calculated from the initial values of the parameters DO constructtsmay be nested to any deth Good programming style requires that an EXIT from a DO occurs as neartothe top orthe end of the loop as possible The IOSTAT specifier may be used with READ to detect an enc offile condition Chapter 6 Exercises 6 1 Write a program to findthe sum of the successive even irtegers 2 4 200 Answer 10100 6 2 Write a program which produces atable of sin x and cos x for angles x from 0 to 90 in steps OE 15 6 3 A person deposits 1000 in a bank Interest is compounded monthly at the rate of 1 per month Write a program which will computethe monthly balan
28. program which will evertually spew vast amounts of data out on the prirter To save time and where the output shoul paper while writingthe program you may want to be able to specify whilethe program is running ld go The following code should help PRN and CON arethe names of ths PC prirter and terminal respectively PEN 1 FILE RIT GI CHARACTER OutputDevice 3 PRINT Where do you want the output prn or con READ OutPutDevice O W OutputDevice 1 Output on designated device 10 6 Internal Files E was mentioned above that the unit specifier in READ or WRITE could be an internal file This is basically a character variable ar array which may be written to or read fiom E g CHARACTER 50 CAPTION WRITE CAPTION 10 YEAR 10 FORMAT Sales figures for the financial year I4 CAPTION couldthen be used as a caption in a graphical display Trternal es provide a general means of converting numeric datato strings and vice versa READ may be usedto reverse the above process In the code below the string 1984 is convertedto an irteger with the value 1984 C STRING 1984 R 10 FORMAT I4 10 7 External HARACTER 30 STRING EAD STRING 10 NYEAR Files Output from a program may ke sert to an external file e g residing permanertly on a disk
29. times element in target row and pivot column DO TarRow 1 N IF TarRow PivRow THEN TarElt A TarRow PivRow A TarRow 1 2 N A TarRow 1 2 N amp A PivRow 1 2 N TarE ct END IF END DO END DO finally extract the inverse from columns N 1 to 2N Inv A 1 N N 1 2 N END FUNCTION Inv 221 END MODULE MatMult Note the following features e The argumert Mat isthe matrixto be inverted Aisthe augmented matrix it must havet wice as many columns as A Mat is assignedtothe firs N columns of A the identity matrix is assigned tothe nigttmost N columns e The number of columns N 1 in Gauss must be replacedby 2 N e Inv handles a zero pivct element by looking down the column underthe pivot until it finds a non zero elemertk If it cannot finda non zero pivct it returns with a message If it finds a non zero pivot in row K it swops row K withthe pivot row PivRow Note how easilythisis done with array sections A temporary row TempRow is allocated from dynamic storage and deallocated after the swop e Finaly the rightmost N columns of A are assignedto Inv and returned Using the amended version of MatMult we can ind the solution of Equation 15 8 in me statement X INV A x B Below is a main program to solve any linear system of equations in
30. 5 2 Logical Type So far four of the five intrinsic data types have been discussed integer real character and complex The time has come to discuss the fourth type logical 51 Logical constants The default kind of logical type has two literal constarts TRUE and FALSE upper or lowercase The value of the default kind parameter is returned in the usual way by KIND TRUE Your compiler may have noncdefault logical kinds these may be used for example for storing logical arrays more compactly Logical expressions We have seen logical expressions briefly in Chapter 3 They can be formed in two ways from numeric expressions in combination with the six relational operetors or from cther logical expressions in combination with logical variables and the five logical operators The relational operators and their meanings with some examples are as follows Relational Operator Meaning Example LT or lt jessthanA lt le 5 LE or lt lessthan or equalB 2 LE 4 A C EQ or E equa B 2 4 A C NE of not equal A 0 GT gt greater than BAKED ee A RAO CS oO GE or gt greater than or equal X gt 0 Logical operators Fortran 90 has five logical operators which operate on logical expressions Logical Operator Precedence Meaning NOT 1 logical negation AN
31. C 8 Array Inquiry Functions ALLOCATED ARRAY TRUE if ARRAY is currently allocated LBOUND ARRAY DIM rank one array holding lower bounds if DIM is absent otherwise lower bound in dimension DIM SHAPE SOURCE rank one array holding shape of SOURCE If SOURCE is scalar result has size Zero SIZE ARRAY DIM scalar size of ARRAY if DIM is absent ctherwise extet along dimension DIM UBOUND ARRAY DIM similarto LBOUND except that it returns upper bounds C 9 Array Construction and Manipulation Functions Note that array elements are manipulated in array element order CSHIFT ARRAY SHIFT DIM r amp urns an array of the same shape and type as ARRAY with every rank one section that extends across dimension DIM shifted circularly SHIFT times If DIM is omitted it has the value 1 If SHIFT is an array it must have the shape of ARRAY with dimension DIM omitted and supplies a separete value for each shift Some experiments should make this clear EOSHIFT ARRAY SHIFT BOUNDARY DIM identical to CSHIFT except that values are shifted off at the end end off shift and boundary values inserted into the vacated positions If ARRAY has an intrinsictype BOUNDARY may be omitted values of zero FALSE or 270 blank are shifted in as the case may be If BOUNDARY is present and scalar it supplies all needed values ifitis an array it must have the shape of
32. F py 36 0 12 0 Yards Feet Cc Theta SORT A A B B Theta Pi 180 Y LOG X X X A A Y EXP 3 T Pi 4 ATAN 1 0 Y 1 COS X 2 1 TAN Y Y ATAN ABS A X aap Chapter 4 4 1 You should g amp a picture of tangents to a curve 4 2 4 0 2 c The algorithm attributed to Euclid finds the HCF ape eT RS EN CA T USA Population inches left Inches is quicker than convert to radians SORT A A B B 2 A B Cos Theta xk COS 3 T 2 Highest Common Factor of two numbers by usingthe factthatthe HCF divides exactly irto the di and that ifthe numbers are equal they are equal totheir HCF 4 3 1 Cy E D F Eos NT gt D F aru F ai 32 5 0 9 Celsius t G vaJ ve H 7 KAB D A B A gt B PRINT B iS B PRINT END IF SE et j m m D D THEN A is greater B is greater fference bet weenthetwo numbers ott REAL X MaxxX INTEGER I MaxPos O 1 FILE MARKS MAxX HUGE 0 smallest most negative number E X gt MaxX THEN X is biggest so far MaxX X MaxPos I record position END IF ND DO RINT MaxX in position MaxPos W ii REAL Sum 0 initialization INTEGER N DO N 1 100 Sum Sum
33. Name CRM Pl P2 Change the two statements that prirt the marks 29 PRINT Name CRM ExmAvg Final PASS PRINT Name CRM ExmAvg Final FAIL Finally change the data fleMARKS by inserting some names don t forget the apostrophes Able RJ 40 60 43 Nkosi NX 60 45 43 October FW 13 98 47 Tf you run the amended program you should get output like this Name CRM Exam Avg Final Mark Able RJ 40 0000000 51 5000000 51 5000000 PASS Nkosi NX 60 0000000 44 0000000 49 3333321 FAIL October FW 13 0000000 72 5000000 72 5000000 PASS Character constants So far we have dealt mainly witht wo of Fortran 90 sirtrinsictypes irteger and real We now come tothe irtrinsic type character The basic character literal constant is a string of characters enclosed in a pair of either apostrophes or quctes Most characters supported by your computer are permitted withthe exception of the control characters e g escape The apostrophes and quotes serve as delimiters and are not part of the constant A blank in a character constant is significart so that B Shakespeare is n the same as BShakespeare Fortran 90 is case sensitive only in the case of character constants so Charlie Brown is n the same as CHARLIE BROWN There are two ways of representing the delimiter characters themselves in a character constart Either sort of delimiter may be embedd
34. I JWVHHQA 1 m Eig EGER I RACT D ER 80 ine L Line I I ER 80 Sentence NO ch gt F py A1 IOSTAT NonBliank TOEnd ADVANC NonBlank 1 Line Blanks 0 use quotes if text contains blanks EN TRIM Line Blanks Blanks 1 PosStop Sentence enclos RINT osStop RINT O I RITE DO J uvvu AH W ND T aal TE CHARACT ER EG RINT EAD onth Ww Day CY MOD MOD INT F ihe RACT Gl R 8 Sunday Wednesday ER Centy Enter day Month Month lt Month gt Year INT 2 6 Month AL in quotes if blanks in text Sentence IND PosStop PosStop 1 wow EX Sentence 1 ADVANC 1 WATI E NO Sentence I I PROGRAM Zeller 9 DIM Ww T DayOfWeek Tuesday Friday F amp amp Saturday ENSION 0 6 Monday eer Thursday Month Year month year Month Year 2 0 Month 11 Year 100 Year Ww T Day Month 12 Year 1 100 year in century now Day Year Year 4 amp Centy 4 2 Centy o 2 i 7 DayOfWeek F ROGRAM BinToDec 0 StrBin LOCATABLI maximum length is 80 7 py EGER EGER D Dec TRI ti Bin N Bin
35. Probability of reaching ship F6 1 PShip END PROGRAM DrunkenSailor Output Probability of reaching ship 89 1 Probability of reaching ship 87 8 14 6 Dealing a Bridge Hand Simulation isthe basis of most computer games T playing cards from a pack of 52 The names of the four suits are assignedto element face values are assigned to componerts 0 to 12 character array is ini blank filled from the right tomake them all the sam To deal a card a random integer in the range 0 to he program inthis section simulates a deal of 13 ts Oto 3 of the character array Suit andthe 13 of the character array Value Note that ifa ialized with a constructor the character constants inthe constructor must be e length 51 is generated i e the 52 cards are represented uniquely by the numbers 0to 51 The main proble misthata given cardmay only be dealt once To its elements are initially zero meaning no cards ensure this an integer array Check is s amp up All have been dealt yet The function RanInt generates a random integer and assigns it to Num ut into the Check Num is checked If itis still zero that card has not yet been dealt so Num is p next element of Hand and Check Num is setto 1 This indicates that card Num has now been dealt If Check Num already has the value 1 when Num comes up it means that card Num has already been dealt so
36. or apostrophes T E g PRINT The square root of 2 is SQRT 2 0 Here are some general rules e Each PRINT statement generetes a new ouput record e The way reals are prirted depends on your particularsysten The FTN90 compileron a 386 for example displays reals between 99 999 and 99 999 in fixed poirt form and all others in exponential form If you want to be fussy you have to use format specifications Chapter 10 E g the following statements will prirt the number 123 4567 in fixed point form over 8 columns correct totwo decimal places X 123 4567 PRINT 10 X 10 FORMAT F8 2 e 6iIfacharacterstringin PRINT istoo long to fit on one line it willbe displayed without a break if amp also appears inthe continuation line PRINT Now is the time for all go amp amp od men to come to the aid of the party Sending output to the printer This may be cone as follows on a PC OPEN 2 FILE prn WRITE 2 This is on the printer PRINT This is on the screen Notethat WRITE must be usedin conjunction with a unit number This is a more general statement than PRINT Summary e Successful problem solving with a computer requires knowledge of the coding rules and a sound logical plan e The compilertranslates the program statements irto machine code e Fortran statements may be up to 132 characters long and may star
37. 10 S 7 9 Emps 7 INTEGER NumScales 7 INTEGER I Above Below REAL AvLevel AvSal Above 0 Below 0 AvLevel SUM S DO I 1 NumScales IF S I lt AvLevel Below Below Emps ELSE Above END IF ND DO vSal D El 1000 SUM S TEGER X 10 AL Mean Dist AD X ean SUM X ist ABS X um X 1 DO I IF Num I AAS 10 1 Mean 208 DWH 10 X T X I ABS X I 2 AB Num Dist END IF D DO Mean Il we m Z 9 5 P 3000 Above Emps I Mean 1 Iitdiz N 3 2 While N MOD Increase J R N Increase N by 2 3 Prit althe s 4 Stop Chapter 10 wee 10 3 CHARACTER INTEGER 1 ch NonBlank 0 282 1 2 7 1 rime courter LS 2500 NumScales gt Dist 20 354 1500 Emps 50 1000 100 400 amp 25 intrinsic SUM intrinsic SUM intrinsic SUM it may be the THEN furthest distance 1000 P lt VN by MOD that s another first one number from mean remainder repeat N P prime INT IO OPE FIL F TEST DO F IO End 1 l for EOF under FTN90 N W E 1 F R I D CLOS Chapter 11 T11
38. But this formula favours the old value of y in computing tt would be betterto say Vier hy A f Xeadhua 0 2 16 13 Xy X th where since this also involves the new value Yew in computing f on the right hand side The problem of course is that Vie is as yet unknown so we can t use it on the rigt hand side of Equation 16 13 But we could use Eulerto estimate predict Yi from Equation 16 12 and then use Equation 16 13 to correct the prediction by computing a better version of Viv which we will call YI So the full procedure is Repeat as many times as required Use Euler to predict y Y hf x Vx Then correct yj to Yia Ve ALS Xue Yin Eoy 2 This is called a predictor corrector method The program Para above can easily be adaptedtothis problem The relevant lines of code which will generate all the entries in Table 16 1 amp once ae DO I 1 N PRINT F5 1 3F12 0 Ty NE NC NO EXP R T NE NE R H NE straight Euler NP NC R H NC Predictor NC NC R H NP NC 2 Corrector T T HEND DO NE stands for the straight uncorrected Euler solution NP is the Euler predictor and NC is the corrector The worst erroris now only 15 Thisis much betterthan the uncorrected Euler solution although there is dill room for improvement 16 5 Runge Kutta Methods There ar
39. F10 2 ADVANCE NO P END DO PRINT get a new lin R R RINC END DO Some sample output with input 0 1 0 2 0 01 Rate 15 yrs 20 yrs 25 yrs 10 00 10 75 9 65 9 09 11 00 11 37 10 32 9 80 20 00 17 56 16 99 16 78 Clearly you should not use the same DO variables in nested loops the compiler fortunately won t allow this Ifthe level of nesting is deeper it will probably help to name the Dos 64 You can see why real DO variables and parameters should be avoided by runningthis program with the outer DO statement replaced by DO R RO R1 RINC andthe statement R R RINC omitted Rounding error makes the iteration court too small 6 5 Non deterministic Loops Deterministic loops all rely on the fact that you can work out exactly what the iter ion count is before the loop starts But in the next example there is no way in principle of working out the erent form of the DO construct is needed eration count so a di A guessing game The problem is easy to state The program thinks of an irteger between 1 and 10 i e generates one at random You have to guess it If your guess istoo high ortoo low the program must say so If your guess is correct a message of congratulations must be displayed A little more thought is required here so a structure plan might be helpful Generate random integer
40. N 1 PRINT Mean XBar PRINT Std deviation Std Try this with some sample data each number on a separate lins 10 5 1 6 2 5 73 5 9 9 1 2 7 65 3 8 7 4 4 You should get a mean of 5 76 and a standard deviation of 2 53 ttotwo decimal places The DIMENSION 100 attrinte inthe type declaration statement for the array X sets aside 100 memory locations with names X 1 X 2 X 100 However the sample data above consists of only 10 numbers so onlythe first 10 locations are used Note that the value of N must be read first and must be correct before the N values may be read Afterthe READ is complete the memory area where the array is stored looks like this X 1 X 2 X 3 vee X 10 Sal 6 2 5 7 Sie 4 4 Now that the data are safely stored inthe aray they may be used again simply by referencing the array name X with an element number e g X 3 So the sum of the firt two elements may be computed as 109 SUM X 1 X 2 This facility is necessary for computing s accordingtothe formula above the data must all be read to compute the mean andthe mean must be computed before all the data is re used to campute s To be fair there is another way of cal ing the standard deviation which doesn t require the us of an array Sx NX N 15 As an exercise rewrite the program without an array reading all the dta irto a single va
41. N N and the vectors x and b as We can write the above system of three equations in matrix form as 2 3 3 N N DN 2 2 3 N S amp S II or even more concisely as the single matrix equation Ax b The salution may then be written as x A b 1 where A isthe matrixinverse of A Le the matrix which when multiplied by A givesthe identity matrix This provides a slightly routeto the solution Gauss reduction can also be usedto invert a matrix To invert the matrix A construct the augmented matrix A J where I isthe identity matrix w WN N N DN 2 2 3 oO e or Oo Oo Now perform a Gauss reduction until the identity matrix has appeared to the left of the vertical line so that the augmented array finally looks as follows 1 0 0f I 1 0 0 1 0 3 2 0 I 0 0 1 0 l l The matrixtothe right ofthe line isthe inverse of A If A is not invertible the process breaks down and a row of zeros appears The solution may then be found directly from Equation 15 8 x 1 y 1 z 0 Our subroutine Gauss can be adapted quite easilyto findthe matrix inverse Itis rewritten below as a function Inv which retums the inverse of its argumert Inv can be included in the module MatMult of Section 15 3 and overloaded with a defined operetor INV for matrix inversion 220 MODULI Ley MatMult INTERFACE
42. ND PROGRAM CrankNicolson Output X 0 1000 0 2000 0 3000 0 4000 0 5000 00 0 2000 0 4000 0 6000 0 8000 1 0000 O1 0 1988 0 3955 0 5834 0 7381 0 7690 02 0 1936 0 3789 0 5396 0 6460 0 6920 COOH 0 10 0 0948 0 1803 0 2482 0 2918 0 3068 Note the use of array sections inthe main program Note also that the subroutine TriDiag can be usedto salve any tridiagonal system and could be made part of ageneral ucilitymodule Chapter 16 Summary e A numerical method is an approximate computer method for solving a mathematical problem which often has no analytical solution e A numerical method is subject to two distinc types of error rounding error in the computer solution and truncation error where an infinite mathematical process like taking a limit is approximated by a finite process e An external or module procedure may be passed as an argument of a procedure An interface block is recommended 245 Chapter 16 Exercises 16 1 Use Newton s method in a program to solve some of the following you may have to experiment a bit with the starting value a x x 10 to real and two complex rocs pe sinx infinitely many rocts g lOS x cosx ee 5x 12x 76x 79 0 two real roots near 2 find the complex rocs as well 16 2 Usethe Bisection method to findthe square roct of 2 taking 1 and 2 as initial values of Xi and Xr
43. Non integer DO control variables are obsolescent these messages are genereted by the FTN90 compile your compiler might have slightly different messages There are a large number of compiler error messages which will be listed in the user s manual that comes with your particular compiler Since the compiler is n as irtelligert as you are the error messages can sometimes be rather unhelpful even misleading Some common examples are given below Inappropriate use of symbol X at line N The name X has been usedto represent morethan one object most probably the program name as well as a varidole The duplicated occurrence will be amp line N Implicit type for X at line N The variable X has not been declared explicitly following an IMPLICIT NONE statement Spelling mistakes in declared variables willbe spotted inthis way Syntax error at line N This is one of the most infuriating messages and covers a multitude of errors e g G 9 8 comma instead of decimal point IF A 0 X 1 instead of in a logical expression IF A 0 THEN X 1 incorrect use of THEN in a simple IF 81 or incorrect placement of a statement after THEN Mie We C2 AE GS unpaired parentheses One wonders why the compiler could n be a little more specific Symbol X referenced but not set at line N This is a helpful message whic
44. PRINT C Carry on PRINT I Initial run PRINT Q Quit PRINT READ Opt PRINT SELECT CASE Opt CASE MO Tem X Vars Val CALL Run CASE I i X Vars InVal T 0 241 CALL Run END SELECT END DO CALL TidyUp END PROGRAM Driver Driver uses both modules and allows two basic options atthe moment to runthe model from its initial values I acto run from the current values C Tf an initial runis selected X is assigned initial values and T is set to zero before Run is called Ifa carry on is selected X is assigned current values and T is left unchanged A sample run using the data in this example is as follows Driver Sample Model C Carry on I Initial run Q Quit Enter your option I Time Prey Pred 0 00 105 00 8 00 1 00 110 88 9 47 2 00 108 32 11365 3 00 98 83 12 57 4 00 O41 4 2 11 26 5 00 90 30 9 24 6 00 95 81 7 98 7 00 104 30 7 99 8 00 110 45 9 34 9 00 108 61 11 48 10 00 99 58 12 52 Depending on your enthusiasm you could extend this skeleton a great deal You could even write a procedure for setting up a new model which asks the user for symbolic names of variables and parameters and which generates the aliasing code for subsequent inclusion into DEqs Thisis very useful for large models 16 7 Partial Differential Equations a Tridiagonal System The numerical solution of partial di
45. CONTAINS SUBROUTINE BUBBLE SORT X TYPE KeyPointer DIMENSION INTENT INOUT X list TYPE KeyPointer Temp temp for swop DO J 1 SIZE X K fewer tests on each pass IF X J Key Mark lt X J 1 Key Mark THEN END SUBROUTINI END Gl Pointers is an array of type KeyPointer which has a single component pointing to StudentRecord t hasthe ALLOCATABLE attribute sothat a dynamic array may be created We could have declared Pointers withthe POINTER attribute however we do not needthis attribute forthe array only forthe componert Since we want to set up Pointers as aliases of the array Student Student must have the TARGET attritate The ALLOCATE statement sets up a dynamic array Pointers with four elements in this case The Ith record from the file is read irto Student I whichis aliased by Pointers I Key The array Pointers is passed to the subroutine BUBBLE SORT Only the lines which differ from the version in Chapter 9 are given here Notethat the number of elements in Pointers does not have to be passed this is obtained directly with SIZE The sortingis done on Pointers I Key Mark insteadof Student I Mark This meansthat atthe end ofthe sort Pointers I Key willpoirttothe student record with the highest mark because of the alias relatimship Note also thatthe ordinary assignments involving
46. Elemental functions to manipulate reals EXPONENT X EXPONENT exponert integer part e of the model forX RACTION X FRACTION fractional part of the model for X ie X2 F NEAREST X S NEAREST nearest different machine number in direction given by sign of real S R RSPACING X RRSPACING reciprocal of relative spacing of model numbers near X i e 2P peg I SCALE X I SCALE X2 al SET_EXPONENT X I real whose sign and fractional part arethose of X and whose exponent I e part is I Le X2 P e p SPACING X absolute spacing of model numbers nearX i 2 A 268 C 5 Bit Manipulation Functions These are based on an integer model like the one in Section C 4 Inquiry function BIT SIZE T maximum number of hits that may be held inthe model for I Elemental functions BTEST I POS TRUE ifbit POS of irteger I has value 1 IAND I J logical AND on all corresponding bits of I and J IBCLR I POS value of I with bit POS clearedto zero IBITS I POS LEN value equalto LEN hits of I darting amp bit POS IBSET I POS value ofI with bit POS sttol H gal O ve H j logical exclusive OR on all corresponding bits of I and J IOR I J logical inclusive OR on all corresponding hits of I and J ISHFT I SHIFT value of I with bits shifted SHIFT places
47. H NTEGER Count EAL DIMENSION 2 g H H 0 TER NTEGER DIMENSION 20 NTEGER DIMENSION 1 CALL SYSTEM CLOCK Count Seed Count CALL RANDOM_ SEED CALL RANDOM NUMBE 188 Num INT 6 R 1 applies to PRINT 2013 Num Output very element Tf Risareal valveintherange 0 1 6 R willbeintherange 0 6 and6 R 1 willbein the range 1 7 Le becween 1 000000 and 6 999999 Discarding the decimal part of this with INT will give an irteger in the required range Note that the array R can be transformed irto the array Num in a single statement Once again initializing the seed ensures that the two runs are different We can do istics on our simulated experiment just as ifit were a real one Forexample we could estimate the mean of the number on the uppermost face when the di also the probability of getting a 6 ncte that R is a scalar now not an array INTEGER PARAMETER Throws 100 INTEGER Count I Num REAL Num6 Mean R INTEGER DIMENSION 1 Seed CALL SYSTEM CLOCK Count Seed Count CALL RANDOM_SEED PUT Seed Mean 0 DO I 1 20 CALL RANDOM NUMBER R Output from two successive runs Mean 3832 Chances of a 6 015 7 Mean
48. One way to do this is to s amp asi the maximum space required when d ining the type StudentRecord by declaring the componert Mark as an array The user will then need to indicate which offering is being entered This is wasteful of disk and memory space if fewer 170 offerings are actually required You may like tothink of alternative solutions Chapter 13 Pointer Variables 13 1 Introduction e Poirter assignment versus ordinary assignment e Pointer states e The NULLIFY statement e The ASSOCIATED irtrinsic function e Arguments withthe TARGET attribute e Dynamic variables ALLOCATE and DEALLOCATI e Danger e Array valued functions e Arrays of pointers e Represernt amp ion of atriangular matrix e Sorting structures J 13 2 Linked Lists 13 3 Hidden Implementations of Abstract Data Types Chapter 13 Summary Chapter 13 Exercises 171 13 1 Introduction Warning Tf you are an ald confirmed Fortran 77 user this charter could damage your health The implementation of pointer variables or simply pointers brings Fortran at last intothe league of languages like Pascal and C Run the following program segment REAL TARGET R 13 REAL POINTER P P gt R R cZ xP PRINT P R You will see that P and R both have the same value
49. Period of investment years READ Period PRINT Interest rate per annum as a decimal fraction READ Rate PRINT PRINT Year Balance PRINT DO Year 1 Period Bal Bal Rate Bal PRINT Year Bal END DO END If you feel up to it try to implement non advancing I O to get each input on the same line as its prompt The next program is a variation on the last one Suppose we have to service four different savings accounts with balances of 1000 500 750 and 12050 We wantto computethe new balance for each of them after 9 interest has been compounded Try it out PROGRAM Accounts processes customers accounts IMPLICIT NONE INTEGER Acct counter REAL NewBal new balance after interest REAL OldBal original balance REAL Rate interest rate Rate 0 09 9 pa DO Acct 1 4 WRITE A ADVANCE NO Old balance READ OldBal NewBal OldBal Rate OldBal PRINT New balance NewBal END DO END Note the effects of indenting the statements inside theDO loop It makes it easier for you to spot the block when you read the program 27 Differential interest rates Most banks offer differential interest retes more for the rich less forthe poor Suppose in the above examplethat the rate is 9 for balances less than 5000 but 12 otherwise We can easily amend the program to allow forthis by deletingthe statement Rate
50. TYP Gl AnotherType INTENT IN Right END SUBROUTIN Gl ig Z J H Z J ERFACE INTRINSIC specifiesthat a name listedisthat of an intrinsic procedure The statement is normally optional but makes it clear tothe reader who may be unfamiliar with the plethora of new intrinsic procedures available under Fortran 90 which procedures are irtrinsic and which are n 256 An intrinsic procedure which is passed as an argument must be specified in an INTRINSIC statement Statements L through N OGICAL declares logical type OGICAL Switch OGICAL TruthTable 4 4 array of logical elements See REAL for attributes which may be specified MODULE defines a module MODULE Clobber END MODULE Clobber NAMI NAMI I I ST is an obscure feature which enables you to specify inthe input stream which items ina LIST group are to be read E g Eal INTEGER A B C NAMELIST MyLot A B C READ NML MyLot Input stream MyLot A 3 C 39 a value for B has been omitted See Chapter 10 for ancther example NULLIFY gives a poirter variable disassociated status which may be tested for by the ASSOCIATED irtrinsic function e g NULLIFY Pl Statements O through P OPEN connects an external fileto a unit The
51. Write a program to determine the leter frequency of asample of textin atext file Assume that blanks only occur singly ctherwise you must first reduce all multiple blanks to single blanks 11 11 Write a program which will read a person s name and address from a disk fileand use the datato write a form letter witha special offerto paint his house The datainthe file should be in the form Jones 31 Campground Rd Tf this cota is used the program output should be as follows Dear Mr We will pairt your house with Sloshon You can have the smartest house in The Jones family will be able to Your neighbours amp number 33 will be amazed The items in italics are read or cerived fi the data inthe fi Jones at half Price Campground Rad walk tall again 11 12 Read up about the intrinsic subroutine DATE AND TIME in Appendix C Use itto writea function TIS which returns the time in seconds including milliseconds elapsed since midnight Such a function could be used to time accurately operations in a program e g sorting 151 Chapter 12 Derived Types Structures Chapter 12 Introduction 12 1 Structures e Defined assignments overloading e Defined operators overloading e Structure valued functions e The TYPE statement e Objets and sub objects 12 2 A Database Student Record
52. also wish to thank my colleague Ruth Smart who collaborated with me on an earlier version of this book for her helpful advice and painstaking reading of the manuscript Finally should like to acknowledge a deep debt of gratitude to my wife Cleone for her continual support and encouragement during the preparation of this book It is hoped this book will give some insight into the ways that computers may be used to solve real problems and that after working through it you will be better able to find out more about this fascinating subject for yourself Epilogue Programming Style Throughout this book the emphasis has been on writing clear coherent programs to solve irteresting problems A program whichis written any oldhow although it may do what is required is goingto be difficult to understand when you go through it again after a month or two Serious programmers therefore pay a fair amount of attention to what is called programming style in orderto make their programs clearer and more readable both to themselves and to her potential users You may find this irritating if you are starting to program for the firs time because you will naturally be impatiert to get on with the job But a Little extra attention to your program layout will pay enormous dividends inthe lonng run especially when it comes to debugging Some hirts on how to improve your program ming style are giv
53. as long as C is first initialized to zero 204 Strictly checks should be performed on the shapes of A and B to ensure that they are consistert The main program below uses this subroutine to multiply matrices of any size IMPLICIT NONE INTEGER I J N M P REAL DIMENSION ALLOCATABLE A B C PRINT n m pe READ N M P ALLOCATE A N M ALLOCATE B M P _ ALLOCATE C N P _ PRINT matrix A READ A I J J 1 M I 1 N PRINT matrix B READ B I J J 1 P I 1 N CALL MyMatMul A B C PRINT C I J J 1 P IT 1 N END Tf you do this sort of thing often it will be worth your whileto write subroutines to read and prirt matrices in ader to make sure that the cata is read by rows At this stage I can confess that Fortran 90 has two intrinsic functions which return a dot scalar product and a matrix product DOT PRODUCT X Y andMATMUL A B However if you are serious about scientific programming it is part of your education to be ableto code a matrix multiplication directly Defined operations for matrix handling Matrix multiplication occurs so frequently in scientific programming thatit would be conveniert to define an operator for it Considerthe module MatMult MODULE MatMult INTERFACE OPERATOR x MODULE PROC
54. A READ A PRINT X 1 initial guess why not DO I Ty 6 X X A X 2 PRINT X ENDDO PRINT PRINT Fortran 90 s value SQRT A END Output Enter number to be square rooted 2 5000000 4166666 4142157 4142135 4142135 4142135 errerrrr re Fortran 90 s value 1 4142135 The value of X converges to a limit which is va Note that itis identical tothe value returned by Fortran 90 sirtrinsic SORT function Most computers and calculators use a similar method internally to compute square rocs and other standardmathematical functions Note e the use of a prompt in a WRITE statementto elicit inout from the user old hands note again that norradvancing I O allows the input on the same line as the prompt e that to pirt an apostrophe in a tring the apostrophe must be repeated e that some pairs of keywords sich as ENDDO do n have to be separated 26 Money again The next program computes compound interest on an initial balance over a number of years Run it for a period of about 10 years and see if you can follow how it works Save it for use in Exercise 3 14 amp the end of the chapter PROGRAM Invest compound growth of an investment IMPLICIT NONE REAL Bal balance INTEGER Period period of investment REAL Rate interest rate INTEGER Year year counter PRINT Initial balance READ Bal PRINT
55. Draw a straigt line joining A and B Move A one unit to the left along the x axis Move B one unit up on the y axis 4 Stop 4 2 Considerthe following structure plan where M and N represent Fortran integer variables Set M 44 and N 28 2 While M not equal to N repeat While M gt N repeat Replace M by M N While N gt M repeat Replace Nby N M 3 Write M 4 Stop a Work through the structure plan sketching the contents of M and N during execution Give the output b Repeat a farM 14 and N 24 45 What general arithmetic procedure does the algorithm carry out try more values of M and N if necessary 4 3 Write a program to convert a Fahrenheit temperature to a Celsius one Test it onthe data in Exercise 3 2 4 4 A builder is given the measurements of five planks in feet and inches He wants to convert the lengths to metres One foot is 0 3048 metres and one inch is 0 0254 metres The measurements of the planks are 4 6 8 9 Y 11 3 and 12 0 e the first plank is 4 feet 6 inches long Store the deta in a file Write a program to display under suitable headings the length of each plank in feet andinches and in metres and to find and display the tctal length of planking in metres Answer the total length is 12 624 metres 4 5 Write a program to read any two real numbers which you may assume are not equal an
56. EXIT END DO remove congrats CALL RANDOM_SEED GET Seed get th time in the loop itself Change the program as indicated below and try running it only the section E NO move up move up ELSE IF now congrats here now move down The equivalent structure plan forthe new version is 1 Generate random integer new seed for another game 2 Repeat Ask user for guess Tf guess is too low Tell him it is too low Otherwise if guess is too high Tell him it is too high Otherwise Polite congretulations Until guess is correct 66 3 Stop The essential difference isthatthe EXIT occurs atthe top ofthe DO block inthe first version but at the end of the block inthe second version There is a more subtle difference however in the first case the condition for exiting is tested amp the top in the second case it is only tested at the end DO conditional EXIT We have seen two further versions of the DO construct DO IF logical expr EXIT block END DO and DO block IF logical expr EXIT END DO both versions may be named The EXIT statement provides a means to exit from an otherwise endless loop t may in fact go anywhere inthe loop However it is best foritto go either at the top or at the end the reader does not then have to search through the loop to find the exit condition
57. LETTER amp ABCDEFGHIJKLMNOPORSTUVWXYZabcdefghijklmnopgrstuvwxyz CHARACTER 10 Word IF VERIFY Word LETTER 0 PRINT It s a word T The irtrinsic subroutine DATE_AND_TIME DATE TIME ZONE VALUES returns the date and time in various forms Recall that a number can be converted to its string represertation and vice versa by writing to or reading from an irternal file Chapter 11 Summary he set of available characters is ordered irto one ar more collating sequences ortran 90 provides access to the ASCII collating sequence haracter variables may be compared and ardered on the basis of the collating sequence haracter expressions may be concatenated T F C e Character substrings may be referenced G G haracter constarts and dummy arguments may be declared with an assumed length using an asterisk e Fortran 90 has a powerful set of character handling irtrinsic functions e Forma specifications may be constructed at runtime using character variables Chapter 11 Exercises 11 1 Write a program wh ich reads some text e g one line irto a variable CHARACTER 80 JINE and counts the number of blanks in it Extend it to remove the blanks 11 2 Write a program which reads a sentence ending in a full stop and prirts it backwards without the full stop You might liketo
58. Note that the aray subscritt precedes the substring subscrirts Assumed character length We have already seenthat a dummy character argument may be declared with an assumed length A named character constart parameter may also be declared with an assumed length if you can t be bothered to count the number of characters E g SUBROUTINE JUNK Word CHARACTER INTENT IN Word CHARACTER PARAMETER Message Can t open file Concatenation The concatenation operator isthe only irtrinsic operator for character expressions e g CHARACTER 5 Initials JK CHARACTER 20 Surname Smith CHARACTER 7 RegNo 123456K CHARACTER 9 UserlId UserId Initials 1 1 Surname 1 1 amp RegNo returns JS123456K Embedded format Character expressions may be usedto construct format specifications during program execution The next code fragment reads an irteger and prirts it out as an ordinal number withthe correct suffix e g 23 is otputas 23rd while 24 is otpt as 24th CHARACTER 2 DIMENSION 0 9 amp SUFF tht rst tnd tedir th th th tht th th CHARACTE LO a PMI S YES shoyu READ N LastDigit MOD N 10 FMT 7 8 SUFF LastDigit replace appropriately PRINT FMT N Character array constructors The elements of a character array in a constructor must all have the le
59. Pascal and C Fortran which stands for FORmula TRANslation wasthe first high level programming language Ik made it possible to use symbolic names to represent mathematical quantities and to write mathematical formulae in a reasonably comprehensible form suchas X B 2 A The idea of Fortran was proposed in late 1953 by John Backus in New York andthe first Fortran program was run in April 1957 The use of Fortran spread so rapidly that it soon became necessary to standardize it so that a program written in the standard would be guaranteed to run at any installation which claimed to support the standard In 1966 the first ever standard for a programming language was published This version became known as Fortran 66 more corredly FORTRAN 66 but the practice of capitalizing acronyms is becoming unfashionable A new standard Fortran 77 was published in 1978 In spite of competition from newer languages such as Pascal and C Fortran continued to flourish so much so that the latest standard Fortran 90 came out in August 1991 This is the version used in this book Connoisseurs of Fortran will be interested in the history of the language sketched by Michael Metcalf and John ReidMetcalf and Reid in Fortran 90 Explained Oxford University Press Oxford 1990 Tf you are already experienced in Fortran you might liketo consult the
60. THEN Final ExmAvg ELSE Final P1 P2 CRM 3 0 END IF IF Final gt 50 THEN PRINT CRM ExmAvg Final PASS ELSE PRINT CRM ExmAvg Final FAIL END IF END DO END As explained above the data are stored in an external file MARKS tomake reading more effaciert For example for a sample class of three students the data could be 28 40 60 60 45 13 98 43 43 47 Le the first student has a class record of 40 with exam marks of 60 and 43 51 5 cl lass record not used whereas the second student s mark should be Run the program as it stands The F construct Her final mark should be 49 3 class record used Inthe above example we see a situation wherethe computer must make decisions whether or not to include the class record and whetherto pass or failthe student The programmer cannot anticipate which of these possibilities will occur when writingthe program so it must be designed to allow for all ofthem We need a conditional branch which is ancther of the most powerful facilities in any programming language A common form of the IF construc as it is called in Fortran 90 is IF condition THEN bl ELSE bl m where condition is a logical expression having a tnth val ock1 ockE ND IF ue of eithertrue or false and block and blockE a
61. The details of how to code this problem are left as an exercise in Chapter 8 Figure 4 5 Quadratic equation struction plan 44 1 Start 2 Input data a amp c 3 If a 0 then lf amp O then lf O then Print Solution Indeterminate else Print There is no solution else w o print only one root equation is linear else if lt dae then Print Complex roots else if 4 ae then w 2 3 print w equal roots else al t Vb2 4 ac 2 4 vol A24 ac 2a Print a4 t a 4 Stop Chapter 4 Summary An algorithm is a systematic logical method for salving a poblem An algorithm must be develooed for a problem before it can be coded A flowchart isa diagrammatic reoresertation of an algorithm A structure plan is a reoresertation of an algorithm in pseudo code A procedure orsubprogram isa separate collection of Fortran statements designedto handle a particulartask and which may be activated invoked whenever needed Chapter 4 Exercises The problems inthese exercises should all be structure planned or flowcharted before being coded irto Fortran 4 1 This structure plan defines a geometric construction Carry out the plan by sketching the construction 1 Draw two perpendicular x and y axes 2 Draw the poirts A 10 0 andB 0 1 3 While A does not coincide with the origin repeat
62. This is an alternative method of program preparation which has advantages when the equivalent flowchart gets rather big It is an example of what is called pseudo code The plan may be written at a number of levels each of increasing complexity as the logical structure of the program is developed For example a first level plan of the temperature conversion problem in Figure 4 1 above might be a simple statement of the problem Figure 4 2 Flowcharting symbols 42 Flow of logic Start Stop Input or assignment of data Processing e g calculation of formulae Header for loop structure Decision End of loop structure Decision two or three way branch lt gt OU000 Output 1 Read Fahrenheit temperature 2 Calculate and write Celsius temperature 3 Stop Step 1 is pretty straightforward but step 2 needs elaborating so the second level plan could be something like this 1 Input Fahrenheit temperature F 2 Calculate Celsius temperature C 2 1 Subtract 32 from F and multiply by 5 9 3 Output the value of C 4 Stop Figure 4 3 Quadratic equation flowchart YES n Solution 2 Complex wea jH o A xy b b gac 2a xy b Wbe 4ac 23 There are no hard and fast rules about how to write flowcharts and structure plans you should use whichever method you prefer or even a mixture The essential point is to cultivate the mental discipline of getting the logic of a program clear be
63. YES or NO see OPEN Ges kal Z m LOGICAL connected CHARACTER 10 acc INTEGER nrec INQUIRE 1 OPENED connected ACCESS acc NEXTREC nrec INTEGER declares objects with irteger type eg INTEGER N X INTEGER List 0 100 See REAL for attributes which may be specified 255 INTENT specifies the irtert attribute for a dummy argument See REAL INTERFACE specifies an explicit irterface for an external subprogram e g INT T RFACE FUNCTION F X REAL INTENT IN X m 2 D FUNCTION F m 2 D INTERFACE Irterfac blocks can also overload procedues with a generic name INTERFACE SuperFung MODULE PROCEDURE IntFung RealFung defined in module END INTERFACE Procedures may be overloaded with an operator e g INTERFACE OPERATOR FUNCTION MyMult A B must be a function TYPE MyType MyMult Gl TYP Gl AnotherType INTENT IN A B END FUNCTION MyMult ea Z J H Z J ERFACE and also with the assignment operator INTERFACE ASSIGNMENT SUBROUTINE MyAss Left Right TYP Gl MyType INTENT IN Left
64. ableto make decisions as we saw briefly in Chapter 3 T is this facility together with its ability to repeat statements endlessly without getting bored which gives the computer its great problem salving power The fundamental decisionmaking construct in Fortran isthe IF construct of which the CASE construct is ancther form 47 5 1 The IF Construct We have seen some examples of the simple IF statement and the construct already Further examples which become more involved are given inthis section Bending moment in a beam A ligtt uniform beam 0 lt x lt L is clamped with its ends atthe same level and carries a concentreted load W at x a The bending moment M at any poirt x along the beam is given by two di formulae depending on the value of x relative toa viz M W L a al x L 2a 0 lt x lt a M Wa aL 2L x 3L 2a L a lt x lt L The following program extract computes the bending moment every metre along a 10 metre beam with a load of 100 Newtons at a pairt 8 metres from the end x 0 INTEGER X REAL A L M W ll aN D L A THEN L A 2 A L X L 2 A pmj x 3 END IF PRINT X M END DO Note that X isan irteger for use inthe DO loop Top of the class Tis 3 M W A A A L 2 L L XK 3 L 2 A A clas
65. and input may also be fetched by a program from such a file This powerful facility provides a means of keeping records which may need to be updated examined and analysed There is a certain amount of jargon that needs to be overcome before we can proceed In Fortran a from the poirt of view file is saidto exist if a program is able to access it Existence is therefore a relative term defined of the program attempting access A file which exists for a program may or may not be empty and it may or may not be connected to that program A file is connected by ass ion with a unit number known tothe program This connection is usually made by an OPEN statement bt certain files may be automatically pre connected 133 A file may be thought of as a stream of data arranged into records The records are all either formatted or unformatted Files may be accessed sequentially or directly normally a particular fil is restricttedto one mode of access If access is direct allrecords must have the same length this is not necessary under sequential access Inthe rest of this chapter we outlinethe main file handling facilities of Fortran 90 More sulstantial examples follow in later chapters File positioning A file has a current position which may be within a record between records ahead of the fi rst record
66. deviation One of the exercises at the end ofthe chapter invites you to write a program to compute 145 the average sentence length ofa sample oftext An important part of the problem isto detect extract and count whole words inthetext The next program reads a text word per line to indicate that whole words have been extracted counting Eis assumed that words are separated by at least one blank a wordisde more nomblank characters So punctuation marks like commas and full stops will not be cou separate words as long as they are not preceded by blanks However punctuation marks are out before printing a word T Al of any length prints out one them as it does so fined as a string of one or nted as Filtered he most important part of the problem isto detect complete words Thistakes time tothink out t fo didn t know the k ften helps to think how you would explain the problem not even the answer to someone who rstthing about it Imagine a stream of characters coming past you How would you character at atime keeping a the current character Ch I we ve found ancther word now when a complete word had passed Surely when a non blank changes to a blank it s the change from nomblank to blank that signals the end of a word Realizing this will give youthe Aha experience
67. following code assigns the first five even integers to the ten elements of X assumed correctly declared DO I 1 5 XL HS 2 oD END DO The same effect can be achieved in a number of di fferert ways with an array constructor X 2 4 6 8 10 or SS C T SO TOP 2 gt 7 A constart array may be ceclared inthis way withthe PARAM ET ER attribute An entire array may be read READ X O f course the exact number of data values must be supplied An enti scalar value X 1 array may be assigned a This is a special case of array assignment which we will encounter again later Reading an unknown amount of data T DO together with the IOSTAT specifier in READ provides a neat way of reading an unknown amount of data irto an array where only the maximum size of the array is given he implied INTEGER PARAMETER MAX 100 REAL DIMENSION MAX X OPEN 1 FILE DATA READ 1 IOSTAT IO X I I 1 MAX IF IO lt 0 THEN N I 1 ELSE 111 The data may be arranged in any format inthe input of values read it is incremented in the implied DO before th detected Note also that on normal file Notethat I is one greaterthan the number it fi m the implied DO nc of Fileenc of filecondition is 9 3
68. gt A and CH lt Z or CH gt a and CH lt z THEN SELECT CASE CH CASE PAT AT ETS LOT IOSA vay TET LET roty u PRINT Vowel CASE DEFAULT PRINT Consonant END SELECT B iSE PRINT Something else END IF END DO TE decides whether a characteris a vowel consonant or something else It stops when the symbol is read This could be programmed ent would be harder to read ry it The general form of CASE is F py EL ECT CASI expr CASE selector1 LE CAS pa selector2 tirely with IF but would produce a lot more code which block1 block2 F CASE D EFAULT blockD EL END SELECT where expr must be irteger character or logical If it evaluates to a partiaular selector that block is executed otherwise CAS T D only one TE does not necessarily have to be the last clause ofthe CASI The general form of the select expr enclosed in parentheses e g CAS E FAULT is selected CASE F D EFAULT is optional but there may be E construct toris a ist of non overlapping values and ranges of the same type as Notethatthe colon may be usedto specii the CASE is selectedif expr evaluatesto vice versa fy a range of values Ifthe upper bound of a range is absent a valuethat is greaterthan or equaltothe lowerbound and
69. of pointers use a Bubble Sortto sort the integer values into ascending order and print the sorted list 13 3 Set up an uppertriangular matrix of N rows and columns with each row represented by a dynamic array of poirters 13 4 Write a program to set up a linked list of integer values read from the keyboard print the list and dispose of it 185 Chapter 14 Simulation Chapter 14 Introduction 14 1 Random Number Generation 14 2 Spinning Coins 14 3 Rolling Dice 14 4 Bacteria Division 14 5 A Random Walk 14 6 Dealing a Bridge Hand 14 7 Traffic Flow Chapter 14 Summary Chapter 14 Exercises Chapter 14 Introduction An extremely powerful application of modern computers is in simulation A simulation is a computer experiment which mirrors some aspect of the real world that appears to be based on random processes or is too complicated to understand properly Whether events can be really random is actually a philosophical or theological question Some examples are radio active decay bacteria division and traffic flow The essence of a simulation program is that the programmer is unable to predict before hand exactly what the outcome of the program will be which is true to the event being simulated For example when you spin a coin you do not know exactly what the result will be 186 14 1 Random Number Generation The intrinsic subroutine RANDOM NUMBER R may be used to simulate random events
70. ooo o A 0 5 1 Cc 0 0 0 ELO We willcallthis matrix A It represents a directed network withthe spies atthe nodes and with arcs all of length 1 where a network is a collection of poirts called nodes The nodes are joined by lines called arcs In a directed network movement e g of information is only possible along the arcs in one direction see Figure 15 2 The matrix A is known as an adjacency matrix with a adjacency matrix 1 in row i and column j if there is an arc from node i to node j or a 0 in that position if there is no arc between those two nodes The diagonal elements of A Le 411 422 etc are all zero because good spies do not talk tothemselves since they might then talk in their sleep and give themselves away Each 1 in A therefore reoreserts a single path of length 1 arc inthe net work Figure 15 2 The network represented by the matrix A 210 poso lt 0 OL O a 20k Ot 0 ON as A 10 00 1 1 0 0 0 If JO 0 2 1 0 toast what is cated A 0 0 0 0 ofxlo 0 0 0 OJ 0 0 0 0 0 00 1 0 0 JO 0 1 0 OJ J0 0 0 0 0 001 1 0 0 011 Of 0 0 1 0 0 Row 2 and column 3 have been emboldened inthe two versions of A above to help interpret A The element 2 in A row 2 column 3 results when row 2 of Ais multipliedterm by term with column 3 and the products added This gives us the scalar product 1x1 0x0 0x0 0x1 1x1 2 The first non zero
71. py OUTINE UpDat HEN not found e Found fa lse ks forthe name ofthe studert whose mark isto be changed and then searches fort The logical variable Found willbe s amp to TRUI E You may betempted here to have an initializ E ifthe student is found Ini ially it must be tion expression in its declaration e g attribute i e its value is retained between The name to be searched for isreadirto Item You may wantto buildin som to facilitate getting an exact match with the name in Student characters in Item and Student F Pie o O on entry again after a successful search mbellishments here Name For example all th Q Name could be converted to uppercase before searching In this example all blanks are rmoved by StripBlanks 162 SUBROUTINE StripBlanks Str CHARACTER Str INTEGER I I 1 DO WHILE I lt LEN_TRIM Str null str won t matter IF Str I I THEN Str I Str It 1 don t increase I yet ELSE I I 1 END IF END DO END SUBROUTINE StripBlanks There is only one subtlety inthis routine If a blank is found in position I itis removed with the substring operation Str I Str I l However I must ng be incremented since ancther blank might have moved up irto position I Ik must therefore be tested again Only when a blank is not found m
72. so that for example S1 S2 returns elements which are members of both 1 and S2 Overloading inthis context means that the operator retains its original intrinsic meaning when the operands are intrinsictypes irteger real or complex inthis case but that it has anew meaning when the operands are of the derived type MODULI Gl IntegerSets IMPLICIT NONE INTEGER PARAMETER MaxCard 100 TYPE SET RIVAT TEGER Cardinality TEGE DIMENSION MaxCard Members T TYPE SET AW El INTERFACE OPERATOR IN MODULE PROCEDURE MemberOf END INTERFACE T INTERFACE OPERATOR MODULE PROCEDURE Intersect END INTERFACE CONTAINS 155 FUNCTION BuildSet V TYPE SET BuildSet INTEGER V INTEGER J BuildSet DO J LE Cardinality 0 1 SIZE V NOT V J IN BuildSet BuildSe uildSe uildSe F a IF B B ELSE PRINT t ole Cardinality Members BuildSet Maximum set siz THI Cardinality lt MaxCard BuildSet EN THEN Cardinality 1 V J 2 O Q Cardinality STOP END IF D IF DO UNCTION BuildSet N o Fl UO El N FUNCTION Card ret INT
73. zero e g INT 3 9 returns 3 INT 3 9 returns 3 Ifthe optimal argument KIND is present it specifiesthe value of the kind parameter ofthe result Otherwise the result has default irteger kind LOG X LOG natural logarithm of real or complex X Notethat an integer argument will cause an eror LOG10 X LOG10 base 10 logarithm of X MAX X1 X2 X3 MAX maximum oftwo or more irteger or real arguments MIN X1 X2 X3 MIN minimum oftwo or more irteger or real arguments MOD K L MOD remainder when K is divided by L Arguments must be both integer or both real NINT X KIND NINT nearest integerto X e g NINT 3 9 retums 4 while NINT 3 9 returns 4 REAL X KIND REAL function converts irtegey real or complex X to realtype e g REAL 2 4 returns 0 5 whereas REAL 2 4 returns 0 0 SIN X SIN sine of real ar complex X SINH X SINH hyperbolic sine of X SQRT X SQRT square roct of real ar complex X TAN X TAN tangert of X TANH X TANH hyperbdlic tangert of X Intrinsic subroutines Fortran 90 also has a number of intrinsic subroutines Subroutines differ sligtly from functions in that they are invoked with a CALL statement and results are returned through arguments They are also described in Appendix C The example below shows how you can display the date andtime t also illustrates the use of character substrings an
74. 0 1 and k 0 01 we will have r 1 and Equation 16 19 becomes Uii j 4u ja T Unija Uy T Uy Putting j 0 then generatesthe following set of equations forthe unknowns U il uptothe midpoint of the rod represented by i 5 i e x ih 0 5 Exact and approximate solutions coincide on the boundaries and amp time t 0 The subscrig j 1 has been dropped for clarity 0 4u u 0 04 u 4u u 0 2 0 6 u 4u u 0 4 0 8 u 4u u 0 6 1 0 u 4u u 0 8 0 8 243 Symmetry then allows us to replace u in the last equation by U 4 This system can be written in matrix form as 4 1 0 0 Ofu 04 1 4 1 0 Ofu jos o 1 4 1 o0 u 12 o 0 14 4 A u 16 0 0 0 2 4 u 146 16 20 The matrix A on the left of Equation 16 20is known as a tridiagonal matrix Such a matrix can be rpeserted by three one dimensional arrays one for each diagonal The system can then be solved very ef working program ficiently by Gauss elimination This will nct be explained here but simply presented in a Care needs tobe taken withthe matrix reoresertation The following form is often chosen b c a b Cy a b c A 3 3 3 an1 bp Ch4 a b L n Noting how the subscri ts run we will have to dime 10 time steps of k 0 01 The step length h is speci nsion as follows A 2 N B N C 1 N 1 The following program
75. 1 ELSE CALL Factorial F N 1 F N F END IF END SUBROUTINE ig Z o ii When I first wrctethis program I put N instead of N 1 by mistake asthe argument in the recursive call Consequently the program could not end since Factorial was always called with N having the value of 10 The escape statement F 1 could never be cuted Be warned The subtlety inthis example is working out whetherto place the statement F N F before or afterthe recursive callto Factorial Try nmnningthe program with F N F before the call 104 to Factorial The difference isthat now F N Fisexecuted on each call instead of a copy being made As a result the lasg execution sets Fto 1 and this is its value on return There are more examples of recursive functions in the exercises A recursive subroutine is used to implement the Quick Sort algorithm in Chapter 9 Chapter 8 Summary Large programs should be broken down into subprograms procedures to perform simpler tasks Subprograms may be irternal or external External subprograms are compiled separately from the main program Module subprograms are subprograms which have been collected into separately compiled modules libraries A program unit is a main program external subprogram or module Irternal subprograms are cortained within program units Subprograms consist of funct
76. 1 MaxCol amp I 1 MaxRow by rows ND SUBROUTINE Grapher SUBROUTINE SetWindow Xmin Xmax Ymin Ymax m N FU m N FU 202 Imports grapher limits to be available as globals REAL Xmin Xmax Ymin Ymax XL Xmin XR Xmax YU Ymax YD Ymin D SUBROUTINE SetWindow NCTION XScale X Scales x coordinate to a column on the screen INTEGER XScale REAL X XScale NINT X XL MaxCol 1 XR XL 1 D FUNCTION XScale NCTION YScale Y Scales y coordinate to a row on the screen INTEGER YScale m isthe maximum column s amp in GraphMod by REAL Y YScale NINT Y YU MaxRow 1 YD YU 1 END FUNCTION YScale END MODULE GraphMod Once again the use of a module with private variables means that it can be changed without reference to any code that uses it The variables XL XR etc setby SetWindow are global tothe module sothat they can be used by all its subprograms The use of an irternal file the character variable MyFormat enables the format specification for the main PRINT statement to be set at runtime according tothe value of MaxCol Inthis example the value of MyFormat is 75A1 The axes may not lie inthe region being plotted this should strictly be checked before attempting to draw them 15 3 Matrices A matr
77. 1 to give p 0zvAR Yo Yu A similartransformation is usedto scalethe element X I column C i irtoa 201 c azaua sc by Xmin and Xmax respectively and 1 ARSAL where L and R arethe left most and right most points on the graph C MaxCol The transformations for R and C are coded in GraphMod astwo functims YScale and XScale e YScale Y I returns R sothat they can be generally available e g to draw the x and y i axes The complete coding for GraphMod is as follows ODULE GraphMod M IMPLICIT NONE INTEGER PRIVATE PARAMETER MaxRow 20 INTEGER PRIVATE PARAMETER MaxCol 75 REAL PRIVATE XL XR YD YU first last down up global CONTAINS SUBROUTINE Grapher X Y Symbol Title General graphing routine arguments described in text INTEGER I J REAL INTENT IN X Y CHARACTER INTENT IN Symbol Title assumed length CHARACTER 1 Point MaxRow MaxCol CHARACTER 10 MyFormat WRITE MyFormat I2 A1 MaxCol internal file Point all blanks initially m really should check whether axes lie in range Point 1 MaxRow XScale 0 0 y axis Point YScale 0 0 1 MaxCol x axis DO I 1 SIZE X Point YScale Y I XScale X I Symbol UY ts row END DO PRINT A80 Title PRINT MyFormat Point I J J
78. 10 the sum of 5 and 3 divided by their product 0 53333 21 the cube roct of the product of 2 3 and 4 5 2 17928 the square of 2r 39 4784 take m 3 1415927 6 10 2107 18 the balance when 1000 is deposited for 5 years at 15 p a compounded monthly 2 5 Translate the following expressions irto Fortran ax bx c 0 o oF 0SXKx 2 3 es x E x 0 5 r at bi ct t 1 1 0 3326x lt 2 6 Suppose that the largest integer on your system is gt Write a Fortran statement which will compute this number bearing in mind that an attempt to compute lt will cause an overflow emor r exp 0 5x N20 g h 2 7 Write a program to calculae x where Fy and a 2 b 10 c 12 use Read to input the data Answer 3 0 2 8 There are eight pirts in a gallon and 1 76 pirts in a litre The volume of atank is given as 2 gallons and 4 pirts Write a program which reads this volume in gallons and pirts and converts itto litres Answer 11 36 litres 2 9 Write a program to calculate petrol gas consumption It should assign the distance travelled in kilometres andthe amount of petrol used in litres and computethe consumption in km litre as wellasinthe more usual fom of litres per 100 km Write some helpful headings sothat your output looks something like this Distance Litres used Km L L 100Km 528 46 23 11 42 8 76 2 10 Write some lines
79. 10 heading DO Month 3 12 Fn Fn 1 Fn 2 PRINT 20 Month Fn Fn Fn 1 En 2 En t Fn o1 Pn END DO Month Population Ratio 127 12 144 0 1 6180 Briefly we have replaced PRINT with PRINT n wheren isthe label inthe range 1 99999 of a FORMAT statement which specifies how the output is laid out The first FORMAT statement prirts the headings T12 tabulates to column 12 before prirting any further output The slash starts a new record line feed The 5 asin 5 repeats what follows immediately Incidentally the best way to get your headings right isto put them in after you have got the rest of the output looking as you want it The second FORMAT statement contrals the output of the variables I3 prirts an integer over 3 columns F7 1 prirts a real over 7 columns with one decimal place F6 4 prirts a real over 6 columns with 4 decimal places FORMAT statements which are nomexecutable in the sense that they don t actually initiate any action are usually grouped together for ease of reference eg ai the beginning of a program 10 2 The PRINT Statement The general form of the PRINT statement is PRINT fmt list where fmt may be one of the following e astatement label referringto a FORMAT statement withthe format specifications in parentheses e g PRINT 10 X 10 FORMAT The answer is F6 2 e an asterisk as in the lis directed I O we have bee
80. 16 4 First Order Differential Equations e Vertical motion under air resistance Euler smethod e Euler s method in general e Bacteria growth Euler s method e A predictar comector_ method 16 5 Runge Kutta Methods e Runge Kutta fourth order famulae e Systems of differential equations a predatar orey model 16 6 A Differential Equation Modelling Package 16 7 Partial Differential Equations a Tridiagonal System e Heat conduction Chapter 16 Summary Chapter 16 Exercises Chapter 16 Introduction A major scientific use of computers is in finding numerical solutions to mathematical problems which have no analytical solutions i e solutions which may be written down in terms of polynomials and the known mathematical functions In this chapter we look briefly at three areas where numerical methods have been highly developed solving equations evaluating integrals and solving differential equations 224 16 1 Equations In this section we consider how to solve equations in one unknown numerically The general way of expressing the problem is to say that we want to solve the equation f x 0 ie we want to find its root or roots x There is no general method for finding roots analytically for any given f x Newton s method This is perhaps the easiest numerical method to implement for solving equations and was irtroduced earlier It is an iterative method meaning that it repeatedly att
81. 2 Ask user assumed male for guess 3 Repeat until guess Tf guess is too Tell him it Otherwise Tell him it Ask him for ancther guess 4 Polite congratulations 5 Stop is correct low then too low too high Before we look amp the whole program let s se how the random irteger is generated The statement CALL RANDOM NUMBER R first generates a random real R inthe range 0 lt R lt l Le 0 1 10 R willbe inthe range 0 10 and10 R 1 willbeinthe range 1 11 i e between 1 000000 and 10 999999 inclusive Using INT on this will then give an irteger in the range 1 to 10 as required Tf you want to play morethan once with different random numbers eachtime you will needto re seed the random number generatorin a specific way each time you runthe program The first time you run the program supply any integer you like for the seed But on subsequent occasions you should use the new seed printed at the end ofthe previous game Detailed discussion of this process is left to Chapter 14 INTEGER FtnNum MyGuess INTEGER DIMENSION 1 Seed REAL R WRITE Seed ADVANCE NO READ Seed 1 user supplies seed CALL RANDOM SEED PUT Seed l CALL RANDOM NUMBER R FtnNum INT 10 R 1 WRITE Your guess ADVANCE NO READ MyGuess DO IF MyGuess FtnNum EXIT
82. 200 0 2E2 200 0 4 12E 2 412 0 7 321E 4 0 0007321 Real constants are stored in exponential form in memory no matter how they are actually written If a real has a fractional part it may therefore be represerted approximately thisis sometimes referred toas finite machine precision Even ifthe is no fractional part the real is stored differently from an integer of the same value E g 43 is an integer while 43 0 is a real They will be represerted differently inme mory The range and precision of real constarts are not specified by the standard Typically reals will f x h f x n n 1 range bet ween Beat n and h with a precision of about seven decimal digits The range and precisio may be specified with a kind parameter 2 5 Names and Variables We have already seen that memory locations can be given symbolic names such as BALANCE and RATE In Fortran 90 names can be given to otherthings apart from memory locations such as the program itself A name must consist of between 1 and 31 alphanumeric characters and must start with a letter The alphanumeric characters are the 26 letters the 10 digits and the underscore _ Fortran 77 users will ncte that names may now be longer than six characters Except inthe case of character strings Fortran 90 is case insensitive i e the names MYNAME and MyNa
83. 26 P should be thought of as an alias of its target R i e Just ancther name for R What happens to R therefore also happens to P Inthis case P is the pointer It must be specified with the POINTER attribute and the type of the variable for which it is going to be an alias Furthermore the variable for which P isto be an alias must be declared withthe TARGET attribute The TARGET attribute is conferred on allthe sub objects of an object which is thus specified The pointer assignment statement above P gt R should be thought of as make P an alias of R or make P point to R I you have encountered poirters in cther languages note that a Fortran 90 pointer is nct an address it is in fact the reference variable of C The pointer assignment above can be illustreted as follows R 5 Now consicer the following code REAL TARGET R 13 REAL POINTER Pl P2 Pl gt R P2 gt Pl PRINT Pl P2 R END Try to work out the result before running it The second painter assignment P2 gt Pl makes P2 an alias of Pl But P1 is already an alias of R so P2 is also an alias of R P1 P2 Pointer assignment versus ordinary assignment 172 Consider the following code REAL TARGET Rl 13 REAL TARGET R2 17 REAL POINTER Pl P2 Pl gt R1 P2 gt R2 TE produces this situation
84. 3 4 Print the value of s Stop This plan may seem trivial to you and a waste of time writing down Yet you would be surprised how many beginners preferring to rush straight tothe computer tryto program step 2 before step 1 Eis well worth developing the mental discipline of planning your program first if pen and paper turns you off why not use your word processor You can ever ernterthe plan as comment lines inthe program The program is as follows g ROGRAM Vertical Vertical motion under gravity IMPLICIT NONE REAL PARAMETER G 9 8 acceleration due to gravity REAL S displacement metres REAL T time REAL U initial speed metres sec PRINT Time Displacement PRINT U 60 T 6 SS URE SoG of Qe FO KD PRINT T S END PROGRAM Vertical The strange way of declaring G makes it a named constant since its value should definitely not change inthe program Named constarts are discussed further below Table 2 1 Numeric intrinsic operators Operator Precedence Meaning Example aK 1 Exponertiation 2 4 24 x 2 Multipliction 2 A 3 DivisionB DELTA 3 Addition or unary plus A 6 9 2 7 Programming Style Programs that are written any oldhow whilethey may do what is required can be difficult to follow when read a few months latey in order to correct or update them and programs that are worth writing wil
85. 3 62 Chances of a 6 0 18 Num INT 6 R 1 Mean Mean Num IF Num 6 Num6o Num6 1 END DO PRINT Mean F6 2 Mean Throws PRINT Chances of a 6 F6 2 Num6o Throws END is rolled 100 times say and Run the program a number of times increasing the value of Throws each time and observe what happens tothe mean andthe chances of getting a 6 14 4 Bacteria Division Ifa fair coin is spun or a fairdie is rolled the di ferert everts e g getting heads or a 6 happen with equal likelihood Suppose however that a certaintype o f bacteria divides irtotwo ina given time interval with a probability of 0 75 75 andthat if it does not divick it dies Since a value generated by RANDOM NUMBER is equally likely to be anywhere bet ween 0 and 1 the chances of it being less than 0 75 are 75 We can therefore simulate this si ion as fallows 189 CALL RANDOM NUMBER R IF R lt 0 75 THE PRINT Count R I am now we ELSE PRINT Count R I am no more END IF R N The basic principle of simulation is that one random number should be genereted for each event being simulated The single evert here is whether or n the bacterium divides 14 5 A Random Walk A drunken sailor has to negotiate a jetty toward his ship The je amp ty is 50 paces long and 20 wide A mate places him inthe middle
86. 9 R S T U W x Y Z tW nN EXE CR AHR SPOS Fe wae Hee TAG om IVA WANS RMAWNeE Gs art Pt ee amie PS I b t ASCI code 127 has the code DEL Under MS DOS this codehas the sane ettect as ASCII BS The DEL code can be gererated by the CT RL BKSP key 273 Appendix E Solutions to Selected Exercises Solutions to the exercises are listed in each Chapter topic Chapter 1 RINT EAD RINT RINT RINT RINT H u a uu yu da ROGRAM EAL C A ND PROG Ener E V ROGRAM Arith FAL A B Ww B Sum Ww Ww Product Quotient RAM Arith gy RINT p a READ E p E Chapter 2 i END PROGRAM Cy YV Ce MRR Df Stored energy Energy Enter A and B Difference Ww T Ww d Ww L Pe MN EL W w w w Ww m comma should be replaced by decimal poirt asterisk shoul d be omitted exponent must be integer comma should be replaced by decimal point decimal poirt n allowed first character must be a letter apostrophes n allowed blanks not allowed decimal poir s not allowed k asterisk n allowed rst character must be a letter 0 allowed but nct recommended 274 mae amaa EAL RINT RINT RINT RINT RINT RINT UU VU AT a who aa w PARAMET ER 2 kx sn ka 2 3 4 2 Pi Pi 3 14159
87. A structure plan forthe bubble sat is as follows 1 Initialize N length of list 2 Readthe lit X 3 Repeat N times with counter K Repeat N K times with counter J EX gt Xn then Swop the contents of Xj and Xj 4 Print the lis X which is now sorted As an example consicer a list of five numbers 27 13 9 5 and 3 They are initially read into the array X Part ofthe computerme mory forthis problem is sketched in Table 9 1 Each column shows the list during each pass A stroke in a row indicates a change in that variable during the pass as the program works down the list The number of tests X gt X 1 made on each pass is also shown in the table Work through the table by hand with the structure plan until you understand how the algorithm works Figure 9 1 Memory during a Bubble Sort 1st pass 2nd pass 3rd pass 4th pass X 1 27 13 13 9 9 5 5 3 X 2 13 27 9 913 5 5 3 3 5 X 3 9 27 35 5 13 33 3 9 9 X 4 5 27 3 3 13 13 13 115 X 5 3 27 27 27 27 4tets 3tets 2tets ltet Sorting algorithms are compared by calculating the number of teststhey carry out since this takes up most of the execution time during the sort On the Ath pass of the Bubble Sort there are exactly N Ktests sothetctal number of tests is 1 2 3 dots M1 N N 1 2 approximately N7 2 for large M For a list
88. ARRAY with dimension DIM omitted and supplies a separate value for each shift MAXLOC ARRAY MASK returnsthe subscricts of the largest element of ARRAY in a rank one array of size equal tothe rank of ARRAY The operation is restrictedto elements corresponding to true elements of MASK if it is presert If there is more than one maximum the first in array lement order is taken MERGE TSOURCE FSOURCE MASK elemental function r amp urns TSOURCE if MASK is TRUE FSOURCE otherwise E g if the three arguments are conformable arrays the firs two are merged under the control of MASK MINLOC ARRAY MASK similar to MAXLOC excegt that the subscricts of the smallest lement are returned PACK ARRAY MASK VECTOR rank one array of elements of ARRAY according to true elements of MASK if VECTOR is absert Otherwise result has size equalto sizen of VECTOR which must have size at least equal to the number of selectedelemerts if t lt n elements i of the result for i gt t are the corresponding elements of VECTOR RESHAPE SOURCE SHAPE PAD ORDER array with shape given by rank one irteger array SHAPE andtype of SOURCE The size of SHAPE must be constart If PAD and ORDER are absent the elements of the result arethe elements of SOURCE in array element order If PAD is presert it must be an array ofthe same type as SOU
89. Arrays as Subprogram Arguments its value would be MAX 1 An array may be passed as an argument to a subprogram ina number of ways The neatest way is shown inthe next program wherethe calculation of the mean and standard devia the subroutine Stats IMPLICIT NONE INTEGER I N REAL DIMENSION 100 X REAL re Std 20 REAL XBar 0 OPEN 1 FILE DATA READ 1 N X I I 1 N CALL Stats X N XBar Std PRINT Mean XBar PRINT Std deviation Std CONTAINS SUBROUTINE Stats Y N YBar S REAL DIMENSION INTENT IN Y REAL INTENT INOUT S YBar INTEGER INTENT IN N INTEGER I YBar 0 S 0 DO I 1 N YBar Ybar Y I END DO YBar YBar N DO I 1 N S S Y I YBar 2 END DO S SQRT S N 1 END SUBROUTINE END The compiler requires that the shape of actual and dummy arguments agree The declar REAL DIMENSION INTENT IN Y 0 ion is relegated to the actual argument The complete syntax forthe dimension in this case is lower bound 112 jon f the dummy argument makes it an assumed shape i e ittakes on whatever shape is imposed by inthis example REAL DIMENSION 0 INTENT IN Y would result in X I correspondingto Y I 1 The lower bound defaultsto 1 if omitted Take
90. Cervartes both died on 23rd April 1616 Shakespeare died on a Tuesday but Cervartes died on a Saturday This is because England had nct yet adopted the Gregorian calendar and was consequently ten days behind the rest of the world The formula will also nct work if you go too far forward 11 4 Write a program which will reada number in binary code of arbitrary length e g 1100 no blanks between the digits and write its decimal value 12 inthis case Hint readthe number as a string and use an irternal file to read the individual characters as irtegers 11 5 Write a program to convert the contents of a text fileto uppercase You can try it out onthe following text if you like Roses are red violets are blue I m schizophrenic and so am I 11 6 Write a program which reads some text from a file removes allthe blanks and prirts it out in five letter groups separated by blanks E g the text Twas brilig and the slithy toves did gyre and gimble inthe wake should be prirted as Twasb rill gand hesli thyto vesdi dgyre andgi mblei rthew abe 11 7 Student numbers at the University of Cape Town are constructed from the first letter and next two consonants of the student s surname the first three letters of her first name padded from the right with Xs if necessary in both cases followed by athree digit number left filled by zeros if necessary to distinguish students f
91. Continue bisecting until the maximum error is less than 0 05 Use Inequality 16 2 to determine how many bisectins are needed 4 f x dx 16 3 Use the Trapezoidal to evaluate using a tep length of h 1 16 4 A human population of 1000 a time t 0 grows amp arate given by dN dt aN where a 0 025 per person per year Use Euler s methodto project the population overthe next 30 years working in steps of a h 2 years b h 1 year and c h 0 5 years Compare your answers with the exact mathematical solution 16 5 The basic equation formodelling radio active decay is dx dt rx where x isthe amount of the radio active substance at time 1 and r isthe cecay rete Some radio active substances decay irto ctherradio active substances which inturn also decay For example Strontium 92 Fy 0 256 per hr decays irto Yttrium 92 2 0 127 per hr whichintumn decays irto Zirconium Write down a pair of differential equations for Strontium and Yttrium to describe what is happening 26 Starting at t 0 with 5x10 atoms of Strontium 92 and none of Yttrium use the Runge Kutta formulae to solvethe equations up to 8 hours in steps of 1 3 hours Also use Euler s method for the same problem and compare your results 16 6 The impala population x f inthe Kruger National Park in South Africa may be modelled by the equation dx dt r bx sinat x where 7 b
92. DO CALL PrintList L CALL Dispose L always tidy up afterwards END PROGRAM TestList By contrast the module ModArray implements the lis as a dynamic aray MODULE ModArray Implementation of abstract data type LIST as a dynamic array IMPLICIT NONE wy Elements dynamic storage DIMENSION POINTE I CONTAINS SUBROUTINE Dispose L TYPE LIST L E I DEALLOCATE ND SUBROUT ole Elements NE Dispose cal SUBROUTINE TYPE LIS EGER EGER N 1 o LOCATII SIZE Ol N 1 OCATE L Elements N Elements OldL Elements N UBROUTINE Insert Insert L Num Tey ss Ty DIMENSION SIZE 7 m oe Elements OldL Num Elements L Elements d He ae POH EI o PAAOOHH ll o o m z UO n SUBROUTINE PrintList L TYPE LIST TARGET L note TARGET attribute INTEGER DIMENSION POINTER P INTEGER I P gt L Elements convenient alias PRINT From the end 183 PRINT P I I m SIZE P 1 1 ND SUBROUTINE PrintList SUBROUTINE SetUp L TYPE LIST L ALLOCATE L Elements 0 size zero at first END SUBROUTINE SetUp END MODULE ModArray user Thetype LIST now has a compon
93. DO conditional EXIT DO WHIL I DO variations which are nct recommended Doubling time of an investment GI Prime numbers Reading an unknown amount of data Taylor series for sine 6 6 Taking Stock Modelling a Population of Gnus Chapter 6 Summary Chapter 6 Exercises Chapter 6 Introduction In Chapter 3 we irtroducedthe powerful DO construct to execute a block of statements repeatedly A sttuation where the number of repetitions may be determined in advance is sometimes called deterministic repetition How loop is only satis called non deterministic Both of these Logically quite different sit DO construct in Fortran 90 58 r it often happens that the condition to end a repeat structure or ied during the execution loop of the loop itself This type of repeat structure is ions are programmed withthe 6 1 Deterministic Repetition In this section we will see how to generalize the DO construct after first considering some more examples Factorials The variable ina DO loop may be used in any expression insidethe loop although its value may not be changed explicitly e g by an assignment statement as a quick and dirty way of temminating the loop early The following program prirts a lis of n and n where ni 1x2x3x x m1 xn Do you trust the real or irteger output and why
94. OPERATOR INV MODULE PROCEDURE Inv ND INTERFACE T m CONTAINS FUNCTION Inv Mat REAL DIMENSION Mat REAL DIMENSION SIZE Mat 1 SIZE Mat 1 Inv must be square 1 DIMENSION SIZE Mat 1 2 SIZE Mat 1 A augmented 1 DIMENSION ALLOCATABLE TempRow spare row PivElt TarElt EGER N number of equations EGER PivRow TarRow Ae m HHP PY U Mat first N columns N A 0 initialize A D identity in cols N 1 to 2N DO PivRow 1 N process every row PivElt A PivRow PivRow choose pivot element IF PivElt 0 THEN check for zero pivot K PivRow 1 run down rows to find a non zero pivot DO WHILE PivElt 0 AND K lt N PivElt A K PivRow try next row K K 4 1 K will be 1 too big END DO IF PivElt 0 THEN it s still zero PRINT Couldn t find a non zero pivot solution rubbish RETURN ELSE non zero pivot in row K so swop rows PivRow and K ALLOCATE TempRow 2 N _ dynamic store TempRow A PivRow 1 2 N K K 1 adjust for overcount PivRow 1 2 N A K 1 2 N K 1 2 N TempRow LLOCATE TempRow throw away PivRow 1 2 N A PivRow 1 2 N PivElt divide whole row now replace all other rows by target row minus pivot row
95. Population Growth 15 7 Markov Chains e A random walk 15 8 Solution of Linear Equations e Gauss reduction e Matrix inversion by Gauss reduction Chapter 15 Summary Chapter 15 Exercises Chapter 15 Introduction In this chapter we look at how to write programs to solve problems involving matrices with examples from such areas as linear algebra networks population dynamics and Markov processes The applications introduced here follow on from Chapter 9 where one dimensional rank one arrays were discussed such arrays are also called vectors In this chapter we deal with arrays having more than one subscript or multi dimensional arrays Although up to seven dimensions are allowed in Fortran we will discuss only two dimensional arrays here since these are the most common An array with two subscripts can represent a table of numbers since one subscript usually the first can label the rows in the table while the second subscript labels the columns This is also the convention adopted for matrices Tables and matrices look exactly the same but since matrices are used in mathematical applications we will deal with them separately 197 15 1 Tables A Concrete Example A ready mix concrete company hasthree factories S1 S2 and S3 which must supply three building sites D1 D2 and D3 The costs in some suitable currency of transporting a load of concrete from any factory to any site are given by the cost table in Fig
96. READ The general form of the READ statement is READ list where list is alist of variables separated by commas Note the fallowing general miles e A single line of input or output is calleda record e g inthe case of a PC fromthe keyboard or on the screen e Each READ statement requires a new input record E g the statement READ A B C will be satisfied with one record containing three values 3 45 whereas the statements READ A READ B 18 READ C require three input records each with one value in it e Whenthe compiler encounters anew READ unread data onthe currert record is discarded and the compiler looks for a new record to supply the deta e Data fora READ may run over onto subsequent records Basically the compiler searches all input records for data until the 1 O Input Output list has been satisfied e Tf there are nd enough data to satisfy a READ the program will crash with an error message Example The statements READ A READ B C READ D with the input records L203 4 7 8 9 10 have the same effect as the assignments VAWP on BR Reading data from text files E often happensthat you needtotest a program by reading alct of data Suppose you were writing a program to find the average of say 10 numbers t becomes
97. REAL INTENT IN X END FUNCTION Fung END INTERFACE XL A initialize XR B N LOG ABS A B E LOG 2 0 1 N must exceed formula value DO I 1 N perform bisections XM XL XR 2 IF Fung XL Fung XM gt 0 THEN XL XM ELSE XR XM END IF END DO END SUBROUTINE Bisect END MODULE NumUtils e The dummy argument Fung is declared in an irterface block inside Bisect e The subroutine returns the number of bisections N and the woot XM The actual name of the function is F tis fined as an extemal function FUNCTION F X REAL REAL INTEN E in F X 3 4 END FUNCTION F A main program to put this all together is then 228 ROGRAM TestBisect SE NumUtils Gt Z J PLICIT NONE A B E X NTEGER N TERFACE FUNCTION F X FAL F EAL INTENT IN X FUNCTION F INTERFACE J H zal D H H RI RI N iw 0 Fl m N 16 2 Integration Although most respectable mathematical functions can be differentiated analytically the same cannot be said for integration There are no general rules for integrating as there are x2 for differentiating For example the indefinite integral of a function as simple as cannot be found mathematically We therefore need numerical methods for evaluating integrals This is actually quite easy to do and depends on the w
98. S urns cardinality of S EGER Card TYPE SET S Card S Cardinality END FUNCTION Card FUNCTION Intersect S1 TYPE SET Intersect INTEGER I Intersect S2 Sly S2 o Cardinality 0 Q DO I IF 51 Intersect Intersect END IF ND DO 1 o Sl Cardinality Members I IN Cardinality Members Intersect S2 THEN Interse C O El al ND FUNCTION Intersect FUNCTION MemberOf LOGICAL MemberOf INTEGER X TYPE SET S MemberOf ANY S END FUNCTION MemberOf Xp Ss fo o Members 1 S SUBROUTINE TYPE SE INTEGER I PrtSet S ES o O PRINT END SUB 20TA ROUTIN S PrtSet Members I F py END MODULI F py A sample main program with cutout follows USE IntegerSets TYPE SET Sl S2 S3 Sl BuildSet 1 2 3 4 5 S2 BuildSet 2 4 6 8 156 XC ded adjust MaxCard Q ct ardinality Cardinality 1 S1 Members I Cardinality o 1 S Cardinality WRITE S1 Pa LOH ADVANCE NO Card S1 CALL PrtSet S1 WRITE S2 Ds Ow ADVANCE NO Card S2 CALL PrtSet S2 WRITE 4 CY ST S 22 vty 13 ADVANCE NO Card S3 CALL PrtSet S3 END Outp
99. Student where StuName is a character variable What this amountsto is a redefinition of the assignment operetorto handle mixed types character and derived in the same way that the intrinsic assignment operetor can already handle mixing of certain types For the first case we need a subroutine Student_From_Name say withtwo dummy arguments which are oftype Student_ Type and character The order of dummy arguments is important and must be the same as the order in which the types appear in the assignment to be redefined This subroutine should assign Student Name explicitly to the character argument Forthe second case we need a subroutine Name_From_ Student say with dummy arguments of type character and Student Type reverse order now This subroutine should assign its character argument to Student Name The most efficient way to handlethis isto set up a module withthe Student_ Type definition and the two subroutines MODULE StudentMod TYPE Student_Type CHARACTER 20 NAMI REAL Mark D TYPE Gl INTERFACE ASSIGNMENT MODULE PROCEDURE Name From Student Student From Name END INTERFACE CONTAINS SUBROUTINE Name From Student String Student CHARACTER String TYPE Student _Type Student String Student Name ND SUBROUTINE el SUBROUTINE Student _From_Name Stu
100. T CAL Se Re Gr Ca DO EN F E CO SU m N SU I EN F E SU El CHARACTER 1 Lights 48 Red 4 Green SYSTEM CLOCK Count ed Coun dTimer eenTimer rs 0 oc Sim 1 T DO Sec 1 10 CALL RANDOM NUMBER IF R lt P END DO IF Lights CALL Go ELSE CALL Stop END IF D DO R G THEN NTAINS BROUTINE Go Lights are green here Seed probability a car arrives in any second random number R 2 GreenTimer GreenTimer Cars Cars 8 IF Cars lt 0 Cars 0 CALL PrintQ IF GreenTimer Green Lights R GreenTimer 0 END IF D SUBROUTIN GI Go BROUTINE PrintQ print the queue of cars INTEGER I PRINT I3 D SUBROUTINE 2X Al PrintQ 2X BROUTINE Stop Lights are red here RedTimer RedTimer 1 CALL PrintQ IF RedTimer Red Lights ce RedTimer 0 ND IF SUBROUTIN Gl Stop OU air Output 194 KKK KKKKKKKK KKKKKKKKKKK BwWNE D D D D KKKKKKKKKKKKK THI 70A1 al THI Cars Cars 1 5a lights are parameters cumulative Sim run for another red at first set counters initialized T 10 sec intervals car arrives advance green timer let 8 cars through may have been less than 8 display traffic queue change l
101. The following method of computing t is due to Archimedes 1 Let A landN 6 2 Repeat 10 times say Replace N by 2N Replace A by 42 4 4 A Let L NA 2 Let U L N1 4 2 Let P U L 2 estimate of 7 Let E U L 2 estimate of error Print N P E 3 Stop Write a program to implementthe algorithm 6 6 Write a program to canpute a takle of the function A f x x sin overthe closed interval 1 1 using incrementsin x of a 0 2 b 0 1 and c 0 01 Usea DO with irteger variable and parameters compute the iteration count explicitly as in Section 6 3 Use your tablesto plat a graph of f x forthe three cases and observe that thetables for a and b givetctally the wrong picture of f x 6 7 The transcendental number e 2 718281828 canbe shown to lethe limit of 1 1 x 77 as xtendsto zero from above Write a program which shows how this expression convergesto e as x gets closer and closer to zero use the real kind with the greatest precision available on your system 6 8 A square wave of period T may be cefined by the funcion 1 0 lt t lt T w T lt t lt 0 The Fourier series for f t is given by tigan tt Hag 2K 1 T Eis of irteresttto know how many terms are needed for a good approximation to this infinite sum Taking T 1 write a program to compute and display the sum to n terms of the series for t from 0 to 1 i
102. The numerical value of the kind parameters is system dependent That is while the integer kinds available under FTN90 are 1 2 and 3 under a differert compiler their values may be 2 4 and 8 although the kinds may have identical properties This raises the question of portability can we write a program which specifies a certain kind and which willrun on any compilerthat supportsthe standard The answer isthat we can usingthe SELECTED INT KIND functicnto name a constant which is intum used inthe type declaretion statement INTEGER PARAMETER K6 SELECTED INT KIND 6 INTEGER K6 I The right hand side of the first statement is an example of a constant expression This guarantees that kind K6 will be able to represent all integers in the range 999999 to 999999 and possibly more Although literal constarts have default kind a different kind may be specified by following the constart with an underscore and an unsigned irteger constant or named irteger consart e g 123 2 123456 K6 specifies 123 with kind 2 which is systen dependent while 123456 is specified with the kind K6 selected by the declaretim above which is portable Clearly the portable form is saferto use and is therefore recommended Inthe evaluation of expressions where operands have
103. Under sequential access records are formatted by default and their length may vary New records may be appended to a sequential file added on at the end but existing records may not be rewritten Under direct access records are unformatted by default must all be the same length and this record length must be specified inthe OPEN statement Under direct access existing records may be rewritten and new records may be appended Direct access is generally more efficiert than sequential access Tf non advancing I O is specified incomplete records may be transferredby READ or WRITE E Chapter 10 Exercises 139 10 1 Give the output of the following two program segments indicate blanks and new lines carefully a 10 FORMAT 1X M 13 N I4 3X X F6 1 T3 E11 4 M 117 N 27 X 0 1235E2 Y 1234 567 PRINT 10 M N X Y b 10 FORMAT I3 1X F6 2 F5 3 I2 20 FORMAT T2 I2 F8 2 T3 F3 1 I4 READ 10 N X Y J PRINT 20 J X Y N Data 0146729 123 61035 10 2 Show how each of the following values will be printed with the edit descriptors shown assume that carriage control has been taken care of a 738 I4 738 I3 Q 38 136 F7 2 gq 100 64 F6 1 9876 545 10 4 f 0 000044009 E9 2 file of any size 10 3 Write aprogram whic
104. a great nuisance to have totype inthe 10 numbers each time you run the program since programs seldom work correctly the first time The following trick is very useful The idea isto put the data in a separate external file which is stored on your computer system g on its hard disk if you are using a PC The program then reads the data from the file each time it is run instead of from the PC keyboard As an example use your word processor to store the following lire inthe ASCII ext file called DATA 3 45 Now use this program to read these three numbers from the file and display them on the screen OPEN 1 FILE DATA READ 1 A B C PRINT A B C END H he OPEN statement connectsthe unit number 1 tothe external file DATA The fom ofthe READ statement shown herethen directsthe comp ilerto look inthe file connectedto unit 1 forits data the unit number may typically be from 1 to 99 Output 19 The PRINT statement is very useful for output of small amounts of data usually while you are developing a program since you don t needto be concerned withthe exact details of the form of the output The general form is PRINT list where list may be a list of constants variables expressions and character strings separated by commas A character string is a sequence of characters delimited by quotes
105. access to graphics facilities draw the phase trajectary for b 1 and ranging beeween 0 01 and 1 0 247 Appendix B Summary of Fortran 90 Statements Statements A through B ALLOCATABLE specifies the ALLOCATABLE attribute for an array See REAL ALLOCATE allocates dynamic storage to a pointer variable at runtime eg REAL POINTER Pl P2 ALLOCATE P1 P2 100 Et may also be used to allocate memory to an allocatahle array REAL ALLOCATABLE X READ N ALLOCATE X N In general ALLOCATE list STAT st Ifthe STAT specifier is presert st is given the value zero after a successful allocation and a positive value otherwise in which case execution continues If STAT is absert execution stops after an unsuccessful attempt to allocate ASSIGN obsolescent and not recommended is used in conjunction with the assigned GO TO GC E g ASSIGN GOTO N 5 TON 4 5 6 will transfer contral to statement 5 after the execution of the GOTO BACKS PACE positions a file before the preceding record e g BACKS PAC BACKS PAC Gl No file is connected to unit 2 bi UNIT u IOSTAT io ERR label See READ forthe meaning of the specifiers BLOCK D ATA not recommended names a BLOCK DATA program unit
106. actual argument must be a variable so that it can be changed or INOUT actual argument must be a variable All dummy arguments should be given an irtert Function dummy arguments should have irtert IN Dummy arguments may be specified OPTIONAL Wanted arguments may be provided ina keyword argument list External subprograms with optional arguments must have an explicit irterface provided by an irterface body An irterface may be used to overload specific subprogram names with a generic name Stubs empty subprograms should be used when developing large programs Subprograms may call themselves directly if they are declared as RECURSIVI function must have a RESULT clause in itsheader to retum its value Gl A recursive Chapter 8 Exercises 8 1 Write aprogram which uses the Newton quotient 105 f x h f x h 3 Aaa at x 1 using successively smaller values of h 1 to estimate the first derivative of A 1 2 10 y 10 cc Use a fincttion subprogram for fix 8 2 Write your own Fortran function to compute the exponential function directly from the Taylor series 6 The series should end when the last term is less than 10 Test your function against the intrinsic function EXP 8 3 WriteafunctionBin N R whichreturnsthe binomial coefficiert break n r n as defined in Charter
107. ae bd y af cd ae bd If ae bd is small rounding error may cause quite large inaccuracies in the solution Consider the system 0 2038x 0 1218y 0 2014 0 4071x 0 2436y 0 4038 84 n NOW and appropriate changes in the coding The exact solution however which can be obtained with that with four figure floating point arithmetic the solution oktained is x 1 714 y 4 286 This level of accuracy may be simulated inthe solution of Ex 5 5 with same statements like AE NINT A E 1E5 1E5 default precision is x 2 y 5 If the coefficierts in the equations are themselves subject to xperimental error the solution of this system using limited accuracy istctally meaningless 7 3 This problem suggested by R V Andree demonstrates another numerical problem called ill conditioning where a small change inthe coefficients causes a large change inthe solution Show that the saluticn of the system x 5 000y 17 0 1 5x 4 isx 7 501y 25 503 2 y 3 using the program for Ex 5 5 with default precision Now change the term on the rigt hand side of the second equationto 25 501 a change of about one patin 12 000 and observe that a tctally different solution results Also try changing this term to 25 502 25 504 etc If the coef anticipatethis sor
108. and a are constants Write a program which e mads values for b a andthe step length A in months e reads the initial value of x and amp e uses Euler s method to compute the impala population e prirtsthe population amp monthly intervals over a period of two years 16 7 The luminous efficiency ratio of the energy inthe visible spectrum to the total energy of a black body radiator may be expressed as a percentage by the formula l 5 1 432 T x e 1 dx 7x10 E 64 771T 4x1 05 246 where T isthe absolute temperature in degrees Kelvin x isthe wavelengthin cm andthe range of irtegration is overthe visible spectrum Taking T 3500 K use Simpson s ruleto compute E firstly with 10 irtervals n 5 andthen with 20 irtervals n 10 and compare your results 16 8 Van der Pol s equation is a second order norlinear differential equation which may be expressed as two first order equations as follows dx dt x dx dt e 1 ae b x The solution of this equation has a stable limit cycle which means that if you plot the phase x X trajectory of the solution the plot of ay against 1 xating at any poirt in the positiv plans it always moves cortinuously irto the same closed loop Use the Runge Kutta method to solve this system numerically with h 0 1 x 0 0 and My 0 If you have
109. and out of the computer is an aspect of what is called data transfer The simplest form of data transfer in Fortran 90 is with READ and PRINT andis called Jist directed More advanced forms of data transfer are discussed in Chapter 10 Input So far inthis chapter variables have been given values by using numeric assignment statements as inthe program MONEY T BALANCE 1000 RATE 0 09 This is an inflexible way of supplying data since to run the program for differert balances or irterest rates you would have to ind and change these statem nts There may be many such assignments ina more complicated program anditisa waste of time to recompilethem every tim you wart to change the data The READ statement however which we saw in Chapter 1 allows you to supply the data while the program is running Replacethesetwo assignment statements with the single statement READ BALANCE RATE When you run the program the compiler will wait for you totype the values of the two variables at the keyboard if you are using a PC an IBM compatible personal L computer They may be on the same line separated by blanks acomma ora slash or on differer t lines You can correct a number with the backspace key while entering it If you are using some other system you may need some advice on how to supply data for
110. and runtothat poirt These facilities are extremely helpful especially for debugging large programs you should make a poirt of finding out and making use of what your compiler offers inthis lire Error interception Fortran 90 has facilities for intercepting and handling certain run time errors such as input output errors e g attempting to read past the end of file or from a non existent file These are discussed later when we deal with advanced I O and file handling 82 7 3 Errors in Logic These are errors inthe actual algorithm you are usingto solve a problem and arethe most difficult to find the program runs but gives the wrong answers It s even worse if you don t realize the answers are wrong The following tips might help you to check out the logic e Try to nun the program for same special cases where you know the answers e Ifyou don t know any exact answers try to use your insight intothe problem to check whether the answers seem to be of the right order of magnitude e Try working through the program by hand or use the debugging facilities to see if you can spect where things start going wrong 7 4 Rounding Error At times a program will give numerical answers to a problem which appear inexplicably different from what we know to be the correct mathematical solution This can be due to rounding error which resul
111. and see You probably didn t spot thatthe numbers in the three age classes tendto a limiting ratio of 24 4 1 This can be demonstreted very clearly if you run the model with an initial population structure having this limiting ratio This limiting ratio is calledthe stable age distribution of the population and again itis a property of the Leslie matrix in fact itis the eigenvector belongingto the dominant eigenvalue of the matrix Different population matrices lead to different stable age distributions The interesting poirt about this isthat a given Leslie matrixalways eventually gets a population into the same stable age di amp ribution which increases evertually by the same growth factor each month no matter what the initial population breakdown is For example if you run the above model with any other initial population it will always eventually get irto a stable age distribution of 24 4 1 with a growth factor of 2 try it and see 15 7 Markov Chains Often a process that we wish to model may be represented by a number of possible discrete i e discontinuous states that describe the outcome of the process For example if we are spinning a coin then the outcome is adequately represented by the two states heads and tails and nothing in between If the process is random as it is with s
112. another random integer is generated This process is repeated 13 times until the array Hand contains 13 unique numbers in th range 0 to 51 This part of the problem may be structure planned as follows Repeat 13 times Get a random number Convet it to an integr Num in the range 0 to 51 va While Check Num 0 repeat Get another random integer Num Set Check Num to 1 Assign Num to the next elemert of Hand 191 To prirtthe hand of cards each element of Hand is subjectedto integer division by 13 The quotient NS willbe inthe range 0 to 3 and givesthe suit The remainder NV willbe inthe range 0to 12 and gives the face value E g the number 43 on division by 13 gives a quctiert of 4 Clubs anda remainder of 3 Six as shown inthe first Ine of output after the program which is as follows PROGRAM IMPLICIT CHARACTE CHARACTE INTEGER INTEGER INTEGER INTEGER CALL SYS BridgeHand NONE R 8 DIMENSION 0 3 Suit Spades Hearts amp Diamonds Clubs Oj R 5 DIMENSION 0 12 Value Two Three amp Four Five Six Seven Eight Nine amp Ten Jack Queen King Ace DIMENSION 0 51 Check 0 Card Count Num NS NV DIMENSION 13 Hand DIMENSION 1 Seed TEM CLOCK Count Seed 1 CALL RAN DO Card Num DO WHI Num END DO
113. as described above The following program which is discussed below reads four records from a direct access file Each record holds a structure variable withtwo components a studert s name anda mark We wartto sort the students irto an order ofmerit IMPLICIT NON Gl INTEGER PARAMETER NameLen 20 INTEGER PARAMETER MaxStu 100 TYPE KeyPointer TYPE StudentRecord POINTER Key END TYPE KeyPointer TYPE StudentRecord CHARACTER NameLen Name INTEGER Mark END TYPE StudentRecord TYPE KeyPointer DIMENSION ALLOCATABLE Pointers TYPE StudentRecord DIMENSION MaxStu TARGET Student INTEGER I TotRecs INTEGER StuLen INTEGER StuRecFile 2 unit for StudentRecord file INQUIRE IOLENGTH StuLen Student 1 OPEN StuRecFile FILE student rec STATUS OLD amp ACCESS DIRECT RECL Stulen TotRecs 4 ALLOCATE Pointers TotRecs DO I 1 TotRecs READ StuRecFile REC I Student I Pointers I Key gt Student I aliases to each Student I END DO 177 T CALL BUBBLE SORT Pointers U RINT Order of merit using pointers RINT U DO I 1 TotRecs A20 I3 Pointers I Key print merit list PRINT END DO CLOSE 2
114. assignment statenent e g BALANCE 1000 sat with a keyword Some keywords encountered so far are END PRINT PROGRAM and REAL Generally there willbe one statement perline However multiple statements may appearon a lineif they are separated by semi colons Forthe sake of clarity thisis recommended only with very short assignments such as 10 Long statements may continue over several lines as discussed below Significance of blanks Blanks are generally n significart i e you can use them to improve readability by indenting statements adding blanks on the left or padding within statements However there are places where blanks are not allowed To be specific it is necessary to define a technical term the token A token in Fortran 90 is a basic significant sequence of characters e g labels keywords names constarts operators and separators these items are all discussed later Blanks may not appear within atoken So INTE GER BAL ANCE and lt arenct allowed lt isan operator whileA B is allowed and isthe same as A B A name constart or label must however be separated fran an adjacert keyword name constant or label by at least one blank So REALX and 30CONTINUE are nct allowed 30 is the label in the second case Comments Any characters following an exclamation mark except in a character string are com
115. builds up on the capacitor according to the formula Q t CV 1 eV ifthe is no charge on the capacitor at time t 0 The problem is to monitor the charge on the capacitor every 0 1 seconds in orderto detect when it reaches a level of 8 unites of charge given that V 9 R 4andC 1 Write a program which writesthetime and charge every 0 1 seconds until the charge firstexceeds 8 units Le the last charge written must exceed 8 Once you have done this rewrite the program to output the charge only while it is strictly less than 8 units 6 17 If a population grows according to the logistic model its size X t atime t is given by th formula KX ANIR K X e X where Xo isthe initial size at time 0 risthe growth reteand K isthe carrying capacity of the nvironment Write a program which will compute and print values of X over a period of 200 years Tak Xo 2 r 0 landK 1000 Experiment with different values of K and see if you can irterpret K hicdlogically 79 Chapter 7 Errors Chapter 7 Introduction 7 1 Compilation Errors 7 2 Run time Errors e Error irterception 7 3 Errors in Logic 7 4 Rounding Error Chapter 7 Summary Chapter 7 Exercises Chapter 7 Introduction Programs seldom run correctly the firt time even for experienced programmers In computer jargon an errorina program iscalleda bug The story isthat a moth sh
116. careful note that the shape is passed not bounds So Tf the lower bounds are the same in the declaretion of the actual and dummy arguments the correspondence will be exact Notethatif Stats is compiled separately as an external subprogram an explicit irterface will have to be provided inthe calling program e g INTERFACE SUBROUTINE Stats Y N YBar S INTEGER INTENT IN se N REAL DIMENSION INTENT IN Y REAL INTENT INOUT nOr YBat END SUBROUTINE END INTERFACE 9 4 Allocatable Dynamic Arrays The program in Section 9 2 reads an unknown amount of data into an array However the maximum size of the array must be declared In programs which have a large demand on memory this could be wasteful A more memory efficiert solution not possible in earlier versions of Fortran is to use dynamic memory The types of variables we have seen so far have all been static variable although this was never mentioned This meansthat when the variable is declared the compiler assigns itto a certain address in memory witha fixed amount of storage space andthere it stays as long as the program is running By contrast chunks of dynamic memory are used only when needed while the programming is running and then discarded This is often a more efficiert way of usingmemory A variable is specified as
117. character TEXT 5 TEXT 6 returns XY dfghijk deletes 5th character TEXT 8 7 returns null To insert a character at position I each character beyond I must be moved up one position first in a DO loop CHARACTER 80 LINE abcdefghijklm IT 5 DO J EN TRIM LINE I 1 LINE J 1 J 1 LINE J J END DO INE I I returns abcd efghijkim The intrinsic function LEN TRIM returns the length of its string argument with trailing blanks removed ctherwise J 1 goes out of range inthe loop Incidentally can you see why the DO loop has to work backwards Tf substring ranges overlap in an assignment the original values are always used on the right hand side eg TEXT 1 8 NAPOLEON TEXT 3 5 TEXT 1 3 returns NANAPEON not in FORTRAN 77 Substrings may be passed by reference to subprograms i e changes to them inthe subprogram are reflected on reuurn However this means that in a call such as CALL JUNK NAME 1 5 NAME 3 9 the characters common to both actual arguments i e NAME 3 5 may not be changed through ither corresponding dummy argument inthe subprogram An array of characters may be ceclared array 147 Gl CHARACTER 80 DIMENSION 60 LINI 7 Then the Ith character of the array element LINE J is referenced as LINE J I I
118. converted by the I edit descriptor The usual form is Iw where w specifies th field wicth The value is right justified inthis field which must allow room for a leading minus sign An altemative form for outputis Iw m which ensures that a minimum of m digits is prirted with leading zeros if necessary E g 16 3 prirts 99 as bb 099 Binary octal and hexadecimal values are also converted by binary the Bw Ow and Zw edit descrictors respectively The minimum number of digits m may also be specified For input the leading leter B O or Z and the celimitersmust be omitted E g READ B4 I will convert the input string 1111 irto the decimal value 15 Real values are converted by the F F EN or ES edit descriptors The F fixed point descrictor has the form Fw d where w defines the tctal field width including a possible sign and the decimal point and d defines the number of digits after the decimal point rounded if necessary E g 12 345 is printed under F8 2 as bb 12 35 On input ifthe input string has a decimal poirt the value of dis ignored E g b1 2345b is read under the descrictor F8 2 as 1 2345 GI Ifthe input string has no decimal poirt the rightmost d digits are taken asthe decimal part 12344 is readunder F7 2 as 123 45 g b There are two other fo
119. doukt you can write an endfile record explicitly with ENDFILE u A file is disconnected with aCLOSE statement t can take the form CLOSE UNIT u STATUS sf 135 wherethe STATUS specifiermay be specified as KEEP or DELETE A file may therefore be erased on disconnection as inthe example above The default value is KEEP unless the file has status SCRATCH in which case the default and only value is DELETE All connected units are automatically closed when a program terminates normally even ifthe are no CLOSE statements anda CLOSE onan unconnected unit does not cause an error However you should make a poirt of closing all your files and no cthers since it shows that you know what you are doing Unformatted I O A file s records may be unformatted The advantage of this is that they take up much less storage than formatted records E g the largest irteger available underthe FTN90 compiler 2 147 483 647 takes up only 4 bytes on an unformatted record since it can be represented with 32 bits but 10 bytes on a formatted record the number of characters required to represent if A sequertial file is formatted by default so the FORM specifier must be used if it is to be unformatted as inthe next example which writes a
120. etc has an o tional irterface block forthe external subroutine DEqs V has original X update X finally update X for return from a run including the initial values for that run Initialize allocates dynamic storage sets up model variable and parameter names and values and also initializes her global variables Note that allthis information could be read from a disk Al The subroutine Run actually runs the model t generates headings integrates the diff which itself could be set up by andher sulbroutine equations RunTime times by calling Runge and finally sets the X Notethat Vars Val is a valid array section the array X can therefore he assigned to it final values of the variables erential from Runge irtegrates the differential equations over o right hand sides TidyUp deallocates dynamic starage and would he the place to close Finally the package is driven bythe main program Driver PROGRAM Driver ne step length dt calling DEqs to supply their les etc Runs differential equations models Model DE must be defined in external subroutine DEqs USE DrGlobal global declarations USE DrUtils Driver subroutines IMPLICIT NONE CALL Initialize Opt PRINT Driver Sample Model PRINT DO WHILE Opt Q AND Opt q
121. extend your program to check whether a sentence is a palindrome i e one which reads the same palindrome backwards as forwards such as REWARD A TOYOTA DRAWER someone who draws Toyctas presumably or Napoleon s classic lament ABLE WAS I ERE I SAW ELBA Assume there is no punctuation and remove all the blanks first 11 3 A formula called Zeller s Congruence may be usedto compute the day of the week given the dte within a certain range of dates The formula is f 2 6m 0 2 k y y 4 c 4 2c modulo 7 irteger part and e misthe month number with January and February taken as months 11 and 12 of the preceding year so March isthen month 1 and December month 10 where the square brackets dencte thy 149 e 6k isthe day of the month e 6c isthe century number e y isthe year in the certury e f 0 means Sunday 1 means Monday etc E g 23rd August 1963 is reoresented by m 6 k 23 c 19 y 63 1st January 1800 is represented bym 11 k 1 c 17 y 99 Write a program to readthe date inthe usual form e g 27 3 1993 for 27th March 1993 and write the given date andthe day of the week in words on whichit falls Hint use an array of characters for the days of the week Test your program on some known dates like today s date or your birthday or 7th December 1941 Sunday The formula will nct work if you go too far back Shakespeare and
122. field is reduced by a factor 10 E g 1 0 isreadunder 2P F3 0 as 0 01 Quantities with an exponent are not affected A scale factor also affects output under E F or G editing Under F a scale factor AP multiplies the output by a factor 10 Under E editing and under G whenthe E option istaken the exponent of thi output is reduced by k whilethe mantissa ismultiplied by 10 130 A scale factor holds for the rest of the format specification or until another scale factor is encountered Tabulation in input or output fields is possible in four ways Tn causes tabulation to position n of the currert T O record TRn or nX tabulates n positions tothe right of the current position and TLn tabulates n positions tothe left of the current position where in all cases tabulation can never go to the left of position 1 On input tabulation can be usedto skip past data orto reread data E g under I1 2X I1 the input string 1234 is readas the two values 1 and 4 On output tabulation can be used inthe conventional way or for partial replacement E g under I3 TL2 I3 the values 911 and 999 are output as 9999 A new record may be started at any point ina format specification by the slash edit descritor t may have a repeat count so isthe
123. implementsthe Crank Nicolson methodto salvethis particular problem over fied by N h 1 2N because of the symmetry r is therefore not restricted to the value 1 although it takes this value inthe program PROGRAM CrankNicolson IMPLICIT NONE INTEGER PARAMETER N 5 REAL A 2 N B N C 1 N 1 U O N 1 G N UX N INTEGER I J REAL H K R T K 0 01 H 1 0 2 N symmetry assumed R K H 2 l set up A B C A R AINI SoZ OR symmetry B 2 2 R C R DO I 0 N initial conditions U I 2 I H END DO U N 1 U N 1 symmetry T 0 PRINT A6 10F8 4 X I H I 1 N PRINT T PRINT F6 2 10F8 4 T U 1 N DO J 1 10 THT EOL G R U 0 N 1 U 2 N 1 2 2 R U 1 N general R CALL TriDiag A B C UX G 244 PRINT F6 2 10F8 4 T UX U 1 N UX U N 1 U N 1 symmetry END DO CONTAINS SUBROUTINE TriDiag A B C X G Solves the tridiagonal system Ax g by Gauss elimination IMPLICIT NON Gl main diagonal lower diagonal upper diagonal unknown RHS working space ry ry ry aru F A ry ry ry HDD DW Dw Z D ppp SP PP EG END DO back substitution X N G N W N DO I 1 N I J N I X J G J C J X J 1 W J END DO ND SUBROUTINE TriDiag m m
124. inthe same file you should use a module Section 8 5 The EXTERNAL statement Tf you accidentally used the name of an intrinsic subprogram for an external subprogram the compiler would by default assume you were referring to the intrinsic subprogram so your external subprogram would be inaccessible You might think you know the names of all irtrinsic subprograms andthatthis problem will n presert itself However you could have a problem when transporting your code to another installation because the standard allows compilers to provide additional irfrinsic subprograms To avoidthis problem the names of all external subprograms should be specifiedin an EXTERNAL statement which should come after any USE Section 8 5 or IMPLICIT statements Naming an external subprogram like this ensures that itis linked as an external subprogram and makes any irtrinsic subprogram withthe same name unavailable This practice is strongly recommended 8 4 Interface Blocks Ifthe compileris to generate calls to subprograms correctly it needs to know certain things about the subprogram name number andtype of arguments etc This collection of information is called 93 the subprogram s interface Inthe case of irtrinsic subprograms intemal subprograms and module subprograms the irterface is always known tothe compiler and is saidtobe explicit However wh
125. is equal to it Le is lexically greater than or equal to it FALSE ctherwise LGT STRING A STRING B TRUE if STRING A follows STRING B in the ASCII sequence FALSE ctherwise ILE STRING A STRING _B TRUE if STRING A precedes STRING B in the ASCII sequence or isequal to it FALSE ctherwise LT STRING A STRING B TRUE if STRING A precedes STRING B in the ASCII sequence FALSE ctherwise SCAN STRING SET BACK position of a character of STRING that occursin SET or zero if no such character The position of the leftmost or rightmost such characteris returned according as BACK is absent FALSE or TRUE VERIFY STRING SET BACK zeroif each character of STRING appears in SET orthe position of a character of STRING that is nct in SET The position of the left most or right most such character is retumed according as BACK is absert FALSE or TRUE C 3 Non elemental Character handling Functions LEN STRING inquiry function number of characters in STRING if scalay or in an element of STRING if itis an array R EPEAT STRING NCOPIES concatenation of NCOPIES of STRING bcth arguments scalar TRIM STRING STRING scalar with trailing blanks removed C 4 Functions Relating to Numeric Representation These functions relate to the models used to represen
126. k 0 004 we get Time Euler Exact 0 00 0 00 0 00 2 00 19 60 18 64 4 00 36 13 32 64 6 00 45 29 41 08 8 00 48 48 45 50 10 00 49 28 47 65 12 00 49 45 48 65 14 00 49 49 49 11 16 00 49 50 49 32 18 00 49 50 49 42 20 00 49 50 49 46 22 00 49 50 49 48 24 00 49 50 49 49 Euler s method gets more accurate if you reduce h e g with h 0 5 the worst error is only about 3 Note that the errors get smaller as terminal velocity approaches In a real proble method in the first place The only check is to use seem to make much di fference e g continue halving 4 untilthe resul m we don t usually know the exact answer or we wouldn t be using a numerical smaller and smaller values of A until it doesn t Its fora fixed t only change by an acceptably mall amount 234 Now let s see what happens when the skydiver opens his parachute The air resistance term will be ferent now For an open parachute k 0 3 is quite realistic We can use the same program as diff before although we need to supply a new starti ng value of 49 49 for v Since h 0 5 worked well before we try the same value now The results are rather surprising fis the time elapsed since the parachute opened Not only does Euler s sol and soon exceeds the speed of ligt example our intuit experimenting will reveal Finally notethat but Time NORROO 00 50
127. m This form is most strongly not recommended If you are tempted to try this in orderto get out of a tricky situation it probably means you have not thought through the logic clearly enough You must be ableto state all the possible conditions for an exit unambiguously either at the top orthe bottom of the loop Some examples where this situation arises are given below The statement CYCLE name transfers cortroltothe END DO statement ofthe corresponding construct so if further iterations are stillto be carried out the next one is initiated Its use is not recommended it makes the logic more difficult to see The DO construct may make use of a tatement label as follows DO 100 I 1 N 100 CONTINUI GI The CONTINUE is a dummy statement which does nothing The construct may also end witha labelled END DO This form is n recommended the labels are not necessary and obscure the logic with redundant information Doubling time of an investment Suppose we have investedsome money which draws 10 irterest per year compounded We would liketo know how long ittakes forthe investment to double More specifically we want a statement of the account each year until the balance has doubled The English statement of the problem hints heavily that we should use a non deterministic DO withthe EXIT condition at the end of the loop The structure p
128. may be used to treat elements by rows e Array constructors may only be usedto initialize one dimensional arrays Ho wever the intrinsic function RESHAPE can reshape a constructor irto any shape e Ther are a number of useful irfrinsic functions for matrix handling 222 e The operetors x and INV were defined for matrix multiplication and inversion respectively e The intrinsic operator cannot be redefinedto multiply arrays since this is an existing intrinsic operation Either a different token must be used or a derived type must be defined Chapter 15 Exercises 15 1 When I first learnt to program there were very few fancy functionsto do allthe work for you Write your own subroutine TRANS A which replaces A by its transpose without using any additional arrays 15 2 Computethe limiting probabilities forthe drunk in Section 15 7 when he starts at each of the remaining intersections intum and confirm that the closerhe startstothe bar the more likely he is to end up there 15 3 Write a program to simulate the progress of the drunk in Section 15 7 down the street Start him at a given irtersection and generete a random numberto decide whether he moves towardthe bar or home accordingtothe probabilities in the transition matrix For each simulated random walk record whether he ends up at
129. nested ogical constarts variables and expressions can only have one of two values TRUE or FALSE ogical expressions may be formed from numeric expressions with relational oper ors lt lt cic e The logical operators NOT AND amp c may be used to form more complex logical expressions from other logical expressions and variables e Fortran has bittmanipulation functions which operate directly on the hits reoresenting integers e The CASE construct may be used to select aparticular adio e The GOTO statement branches unconditionally and shouldbe avoided at all costs Chapter 5 Exercises 5 1 Write a program which reads two numbers which may be equal and writes out the larger one with a suitable message or if they are equal writes out a message to that effect 5 2 Write a structure plan and program forthe following problem read 10 integers and write out how many of them are positive negative or zero Writethe program with an IF construct and then rewrite it using a CASE construct 5 3 Design an algorithm draw the flowchart or structure plan fora machine which must givethe correct amount of change from a 10 note for any purchase costing lessthan 10 The plan must specify the number andtype of all nctes and coins inthe change and shouldin all cases give as few notes and coins as possible Define y
130. no just swop the value in position L 41 withthe value in position R 30 32 19 30 14 28 8 72 41 87 33 L Li R R We can now carry on moving Land R subject tothe niles stated above until we get tothis scene 32 19 30 14 28 8 72 41 87 33 L R E R However the situation now is different L and R have crossed so we must have found the partition poirt itis at position R All that remainsto be done now isto swop the values at L 32 and R 8 giving us a partitioned array with 32 as the partition 117 19 30 14 28 32 72 41 87 33 R L R We can now partition any problem with its left most value So the resulting subproblems can be partitioned in the same way We simply continue partitioning subproblems until the subproblems have only 1 member which must he sorted Thistype of divide and conquer algorithm is what recursion was made for The following program implements it recursively IMPLICIT NONE INTEGER PARAMETER N 100 size of list REAL DIMENSION N 2 List list to be sorted INTEGER I counter REAL R random number DO I 1 N CALL RANDOM_NUMBER R List I INT N R41 random integers in range 1 N END DO PRINT 10 List print unsorted list 10 FORM
131. of Fortran which will exchange the contents of two variables A and B using only one additional variable T 2 11 Try the previous problem without using any additional variables 2 12 Try to spot the syntax errors i e mistakes in coding rules inthis program before running it on the computer to check your answers with the error messages generated by your compiler PROGRAM Dread ful REAL A B X X Y B 67 Woy The answer is B 5 6 X PRINT END 2 13 A mortgage bond loan of amount L is obtained to buy a house The interest rate ris 15 0 15 p a The fixed monthly payment P which will pay offthe bond exactly over N years is given by the formula Fy Write a program to compute and prirt Pif N 20 years andthe bond is for 50 000 You should get 658 39 22 T s interesting to see how the payment P changes with the period N over which you pay the loan Run the program for different values of N use READ See if you can find a value of N for which the payment is less than 625 Now go back to having N fixed at 20 years and examine the effect of different interest rates You should see that raising the interest rete by 1 0 01 increases the monthly payment by about 37 2 14 It s useful to be ableto work out how the period of a bond repayment changes if you increase or decrease your monthly payment P The
132. of five numbers there are therefore 10 tests but for 10 numbers there are 45 tests The computertime needed goes up as the square of the length of the list The program below uses the subroutine Bubble Sort to sort 100 random numbers It departs shi ghtly from the structure plan above which will make N 1 passes even if the list is sorted before the last pass Since most real lists are partially sorted it makes senseto check after each pass if any swops were made If none were the lis must be sorted so unnecessary andthereforetime wasting tests can be eliminated Inthe subroutine the logical variable Sorted isusedto detect when the list is sorted and the outer loop is coded instead as a non deterministic DO WHILE loop IMPLICIT NONE INTEGER PARAMETER N 100 size of list REAL DIMENSION N se Erst list to be sorted INTEGER I counter REAL R random number DO I 1 N CALL Random Number R List I INT N R 1 random integers in range 1 N END DO PRINT 10 List print unsorted list 10 FORMAT 13F6 0 CALL Bubble Sort List sort PRINT 10 List print sorted list CONTAINS SUBROUTINE Bubble Sort X REAL DIMENSION INTENT INOUT X jist INTEGER Num size of list REAL Temp temp for swop INTEGER J K counters LOGICAL Sorted flag to detect
133. of the operation is an array of the same shape One of the operands may be a scalar in which case itis used in the operation on each element of the array operand the scalar is considered to have been broadcast to an array of the same shape as the array operand E g given the declaration REAL DIMENSION 10 X Y the following are examples of array expressions XO p Y result has elements X I Y I X K Y result has elements X I Y I XR result has elements X I 3 X SQRT Y result has elements X I SQRT Y I X result has elements TRUE if X I Y I and FALSE otherwise Note that when an array is the argument of an elemental function the function operates on each element of the array Two arrays of the same shape are conformable A scalar is conformable with any aray Note that binary operations apply to corresponding positions in the extet not to corresponding subscris E g X 2 5 Y 4 7 has elemert values XE ae TF2 jy E S ye By Aye Ba Array assignment An array expression this includes a scalar expression may be assignedto an array variable of the same shape Each element of the expression is assigned to the corresponding element of the target array Again correspondence is by position within the extent rether than by subscrict value E g REAL DIMENSION 10 X Y REAL
134. problen how to simulatethe flow of a single line of trafficthrough one set of traffic lights We make the following assumptions you can make additional or differert ones if like 1 Traffictravels straight without tuming 2 The probability of a car arriving at the lights in any one second is independent of what happened during the previous second This is calleda Poisson process This probability call it p may be estimated by watching cars at the intersection and monitoring their arrival pattern In this simulation we take p 0 3 3 When the lights are green assume the cars move through at a steady rate of say eight everyten seconds 4 Inthe simulation we willtake the basictime interval to be ten seconds so we want a display showing the length of the queue of traffic if any at the lights every ten seconds 5 We will set the ligts red or green for variable multiples of ten seconds For the sample run below the lights are red for 40 seconds Red 4 green for 20 seconds Green 2 The simulation runs for 480 seconds T 48 PROGRAM Traffic IMPLICIT NONE INTEGER Cars number of cars in queue INTEGER Count system count INTEGER Green Red period lights are green red INTEGER GreenTimer counter for green lights INTEGER Sec Sim counters INTEGER RedTimer counter for red lights INTEGER T period of simulation 193 R INTEGER DIMENSION 1 1053 mi i R A ErP AL HR
135. program totest this theory by running it for different values of p and estimating p E in each case 14 5 Dribbolefire Jets Inc make two types of aeroplane the two engined DFII and the four engined DFIV The engines areterible and fail with probability 0 5 on a standard flight the engines fail independently of each other The manufacturers claim that the planes can fly if at least half of their engines are working i e the DFII willcrash only if both its engines fail whilethe DFIV will crash if all four if any three engines fail You have been commissioned by the Civil Aviation Board to ascertain which of the two models is less likely to crash Since parachutes are expensive the cheapest and safest way to do this isto simulate a large number of flights of each model For example two calls of RANDOM NUMBER could represent one standard DFIT flight if both random numbers are less than 0 5 that fligt crashes otherwise it doesn t Write a program which simulates a large number of flights of both models and estimatesthe probability of a crash in each case If you can run enough simulations you may get a surprising result Incicertally the probability of n engines failing on a given flight is given by the binomial distribution bht you do n need to use this fact in the simulation
136. readable programs are presented This book has developed out of notes originally written as a supplement to lectures for students taking courses in applied mathematics at the University of Cape Town with no prior experience of computing It can therefore be used as a teach yourself guide by anyone who wants to learn FORTRAN 77 officially known as FORTRAN ANSI X3 9 1978 the current international standard which is the version used here Although this is primarily a text for beginners the more experienced programmer should be able to find plenty of interest particularly in the applications He may even learn something The appendices contain summaries of all the FORTRAN 77 intrinsic functions and statements including those which are not recommended for stylistic reasons with examples of their general usage No specialized mathematical background is needed to follow most of the examples There are occasional forays into first year university mathematics but these are self contained and may be glossed over without loss of continuity you may even find them instructive Thanks are due to John Newmarch of the University of Cape Town Information Technology Services for his critical reading of the original manuscript on which this book is based and for his invaluable suggestions regarding programming style Thanks are also due to the generations of students who have patiently endured my efforts to improve my methods of teaching computing
137. record E CHARACTER 20 NAME E INTEGER I INQUIRE IOLENGTH LEN NAME OPEN 1 FILE LIST STATUS REPLACE ACCESS DIRECT amp RECL LEN DO I 1 6 READ NAME WRITE 1 REC I NAME write to the file END DO DO I 1 6 READ 1 REC I NAME read them back PRINT NAME END DO 136 WRITE 1 RE QO ll Ww q O N zj Pe change the third record DO I 1 6 READ 1 REC I NAME read them back again PRINT NAME END DO CLOSE 1 END Note that a direct access file behaves like an array In fact if memory is in short supply data can easily be handled with a direct access file rather than in an array If the file is sord on a RAM virtual disk there is practically no difference in access time The record number is given by the REC specifier in the READ and WRITE statements which otherwise have the same forms as for sequential files The INQUIRE statement This statement may be used to ascertain the status and attributes of connected files and unit numbers and the record length of an output lis t has three forms INQUIRE by output list as above I
138. since there are always enough males to go round Suppose for our modified rabbit model we have three age classes with Lone came and 3 members respectively We willcallthem young middle aged and oldaged for convenience We willtake our X F 0 F 12 so that oldsters 3 The probability of survival from youthto middle age is onethig so Suppose the fertilty rete for middle aged rabbits is 9 so time unit as one month so x are the numberthat were born duringthe current month and which willbe consicered as youngsters at the end ofthe month x arethe number of middle aged rabbits at the end of the month and 3 the number of oldsters Suppose the youngsters cannot reproduce LD alet P 1 3 P 05 while no less than half the middle aged rabbits live to become oldsters so we are assuming forthe sake of illustretion that all old aged rabbits die at the end of the month t his can be corrected easily With this information we can quite easily compute the changing population structure month by month as long as we have the population breakdown to start with If we now dencte the current month by ft and next monthby f 1 we can refertothis month s youngsters as Xi andto next month s as X t 1 can then write a scheme for updating the popul Hi X t 1 F X t F X t X t 1 PX t X t
139. subprogram do not nomally retain their values between calls unless they have the SAVE attribute eg REAL SAVE Temp Gl attoibute socal variables which are initialized automatically have the SAV ed with SAVE A dummy variable may n be speci Subprograms as arguments We have seen that actual arguments of a subprogram may be variables or expressions A subprogram name may also be passed as an argument This is discussed in Chapter 16 where there is an appropriate example 8 8 Generic Subprogram Names Overloading You may have wondered having seen how actualand dummy arguments must match exactly intype and number how some of the irtrinsic functions manage to accert arguments of morethan onetype For example the argument of ABS may be integer real or even complex The answer is to use a neat trick provided by Fortran 90 overloading Overloading isa general facility provided by many modem programming languages Inthis context itisthe abilityto calla number of different subprograms withthe same generic name In principle subprograms with different specific names are written for different types of arguments their specific names are then overloaded by a single generic name for all of them The generic name is called the compiler decides which specific name to invoke behind the scenes according to the type of the actual arguments
140. term arises because there is a path from node 2 to node 1 which we will dence by 2 1 followed by a path 1 3 giving a composite path 2 1 3 of length 2 i e from Boristo Cyril via Alex The second non zeroterm arises becausethereis a path 2 5 followed by a path 5 3 Giving a second composite path 2 5 3 of length 2 Le from Boristo Cyril again but via Eric this time It is clear that the entries in A represent the number of paths of length 2 bet ween the various nodes inthe network on the strict understanding that all arcs are of length 1 There are therefore only four paths of length 2 two from Boristo Cyril as we have seen one from Boristo Denisov and one from Ericto Cyril If we now multiplythe matrix A by A again to form the third power of A we get the rather dull matrix 00000 0010 0 4 0 00 0 0 00000 0 0 0 0 0 The single 1 in A tells us that there is only one path of length 3 in the network ie with two irtermediaries and that itis from Boristo Cyril Drawing the network or altematively examining the appropriaterow and column in A and A that give risetothis singleentry in A revealsthat the actual route is Boris Eric Denisov CyriL If we now compute A we will find that every element is zero such a matrix is called the null matrix signifying that there are no paths of length 4 inthe network which can be verified by in
141. that problem solvers rave about So the essence of the problem is to read the text one record of the previous character O1dCh in orderto compare it with f the previous character is nor blank w hen the current one is blank The rest is just mopping up OldCh must be initializedto a blank to startthe ball rolling Ifthe last character inthetext is a nomtblank the above argument wil n catchthe last word so it s necessary to check for this after completion of the DO WHI E loop Nor advancing READ must be usedto get one cl haracter at atime The IOSTAT specifier returns a value of 1 under FTN90 when the endof file is ncountered The intrinsic function INDEX is usedto determine whetherthe currert characteris alphabetic Inthe form used here it hastwo arguments The irst is a character constant L ETT ER consisting of allthe upper and Lowercase letters The second isthe current character Ch INDEX returnsthe position of Ch in LETTER if it occurs there or zero ctherwise IMPLICIT NONE CHARACTER OldCh Ch CHARACTER BL CHARACTER PARAMETER LETTER amp ABCDEFGHIJKLMNOPORSTUVWXYZabcdefghijklmnopgrstuvwxyz INTEGER WORDS 0 INTEGER IO 0 OPEN 1 FILE TEXT OldCh BL
142. the j amp y and stil aie reves Get a random number R for the next sep If R lt 0 6 then Move forward to the ship Otherwise if R lt 0 8 then Move port de Otherwise Move starboard If he got to the ship then Count that walk as a success 3 Compute and print estimated probability of reaching the ship PROGRAM DrunkenSailor IMPLICIT NONE INTEGER Count system clock to seed random number INTEGER NSafe 0 number of times he makes it INTEGER DIMENSION 1 Seed seed for random number generator INTEGER Sims 1000 number of simulations INTEGER Steps 0 number of steps taken on a given walk INTEGER Walks counter INTEGER X Y position on jetty REAL Se PSH probability of reaching ship REAL Catan st random number CALL SYSTEM CLOCK Count Seed Count CALL RANDOM SEED PUT Seed seed from system clock DO Walks 1 Sims 190 Steps 0 X 0 Y 0 each new walk starts at the origin DO WHILE X lt 50 AND ABS Y lt 10 AND Steps lt 10000 Steps Steps 1 that s another step CALL RANDOM NUMBER R random number for that step IF R lt 0 6 THEN which way did he go X X 1 maybe forward ELSE IF R lt 0 8 THEN Y YH 1 maybe to port B iSE y Yous 1 maybe to starboard END IF END DO IF X gt 50 NSafe NSafe 1 he actually made it END DO PShip NSafe 100 0 Sims avoid integer division PRINT
143. the left and right hand sides of the assignment eg n UBROUTINE MatFromScalar Mat X REAL X TYPE MATRIX Mat Elt X END SUBROUTINE MatFromScalar DIMENSION Mat The following irterface block isthen needed INTERFACE ASSIGNMENT MODULE PROCEDURE MatFromScalar ND INTERFACE m TE would be a nice project to build these facilities into a working module Unfortunately FTN90 version 1 2 would n compile it Tf you do a l of heavy number crunching you might need to use double precision real kind 15 4 Array Handling Features Array expressions Eis worth recallingthat whenthe intrinsic operators are appliedto matrices they are appliedto each element of the matrix The expression1 A will n therefore retumthe matrix inverse of A but rather a conformable array with every element the reciprocal of the corresponding element of A Array sections Consider the array C representing the cost table in Figure 15 1 The statement A C 1 2 1 2 C 1 2 2 3 where A has shape 2 2 addst wo sections of C The first consists of the firstt wo rows and columns and the second consists of the firt two rows andthe second and third columns The statement is therefore equivalert tothe matrix addition 3 12 12 10 15 22 17 18 18 35 35 53 Note that the addit
144. the original contents of BALANCE is not lost A number of questions have probably occurred to you by now such as e What names may be used forme mory locations e How can numbers be represented e What happens if a statement won t fit on one line e How can we organize the output more neatly These questions and hopefully many more will be answered in the following sections 2 2 Program Layout The general structure of a simple Fortran program is as follows items in square brackets are optional PROGRAM program name declaration statements executable statements ND PROGRAM program name m As you can see the only compulsory statement in a Fortran program is END This statement informs the compiler the there are no further Fortran statements to compile The n ion END PROGRAM program name means that the program name may be omitted fromthe END statement but that ifthere is a program name the keyword PROGRAM may not be anitted Statements Statements form the basis of any Fortran program and may contain from 0 to 132 characters a statement may be blank blank statements are encouraged to make a program more readable by separating logical sections Earlier versions of Fortran insistedthat certain parts of a statement start in certain columns Fortran 90 has no such restriction All statements except the
145. the overall survival rete for calves Obviously this year s yearlings can only come from last year s calves sob lt 1 Forthe cthertwo age groups life is fairly uncomplicated Their members die of practically only one cause Lion attack This is modelled as follows t seems that lion are indiscriminate in their attacks on all groups except the calves Therefore the number of yearlings taken by lion is in diret proportion to the fraction of yearlings in the tctal non calf population and so on Of course the number taken in year k is also in proportion to the number of hunting lion in year k call this Aine So we can model the number of two year olds and adults with AV y t W bat Yk and _ A t We Wp W t j Yp t W where g isthe lion kil vete number of gnu taken per lion per year 73 The order in which these equations are computed is important We 1 and computed before C 1 After consultation with game rangers a is estimated as 0 45 and a as 0 15 Starfield and Bleloch The lion killwateis between 2 5and 4 lion have other choices on their menu and calf survival bis between 0 5 and 0 7 More precise values of g and b for each year were found experimentally by seeing which values gave atctal population that agreed more or less withthe annual census figures Fittingthe model to the census data was further complicated by the culling killing
146. the relatimshijp numbers F Fa tFn given that 0 F 1 P x x 8 7 The first three Legendre polynomials are a x i and Baje y 1 2 l l There is a general recurrence formula for Legendre polynomials by which they are defined recursively n 1 P x 2n 1 xP x NP__ x 0 ne a recursive Fortran function P N X to generate Legendre polynomials giventhe form of X for a few values of X and compare your Defi P 0 and P x results with those using the analytic form of given above P Use your function to compute P 2 107 Chapter 9 Arrays Chapter 9 Introduction 9 1 Mean and Standard Deviation 9 2 Basic Rules and Notation e Reading an unknown amount of deta 9 3 Arrays as Subprogram Arguments 9 4 Allocatable Dynamic Arrays 9 5 Top of the Class 9 6 Sorting a List the Bubble Sort 9 7 Sorting a List Quick Sort 9 8 More Array Features e Array constructors e Array ions e Initializing anays with DATA e Array expressions e Array assignment e The WHERE construct e Array valued functions e Array handling irtrinsic functions Chapter 9 Summary Chapter 9 Exercises Chapter 9 Introduction In real programs we often needto handle a large amount of data in the same way e g to find the mean of a set of numbers orto sort a list of numbers or names orto analyse a set of stu
147. the statement J EALLOCATE Pl is executed it is clearthat P1 is disassociated andthe dynamic variable to which it was pointing destroyed What is not so clear however isthat P2 is also affected since the object it was aliasing has disappeared A reference to P2 will probably nct cause a program crash but it will produce unpredictable results H he second problem is that of unreferenced storage Consider the following REAL DIMENSION POINTER X ALLOCATE X 2000 Tf X is nullified or set to point somewhere else without first deall ing it there is no way to refer tothat block of memory and so it cannot be released The solution isto deallocate a dynamic object before modifying a potrterto it Array valued functions Sometimes one may want to set up a function to return an array of varying size but a function may not be declared withthe ALLOCATABLE attribute However a function may be declared with the POINTER attributes and this can achieve the same effect The function Vector below returns its array argument with elements sorted in ascending order IMPLICIT NON INTEGER DIM ma F py m F ai NSION 10 X 3 6 9 1 56 4 6 O O 8 PRINT 2013 Vector X CONTAINS FUNCTION Vector A INTEGER DIMENSION POINTER Ve
148. through Z TARGET specifies the TARGI the name is written without parentheses ET attribute for an object which isthe target of a poirter REAL TARGI P1 gt R F py REAL POINTE ik R See also REAL R Pil TYPE defines a cerivedtyps ag TYP Gl 262 Person PRIVATE if no access allowed to components CHARACTER 20 Name END TYPE Person Objects of derived type may be declared e g TYPE Person DIMENSION INTENT IN Town TYPE Person Me USE enables access to the entities in a module by use association USE MyModule only one module per USE USE YourModule Other possibilities are USE YourMod MyPlonk gt YourPlonk MyPlonk is an alias l for object YourPlonk in the module USE USE YourMod ONLY This That access only to This and That WHERE performs operations on selected aray elements There are two forms The WHERE statement has the form REAL A 20 20 WHERE A gt 0 A 1 all elements gt 0 replaced by 1 The WHERE construct looks like this INTEG T R A 20 20 WHERE A gt 0 A 1 all positiv lements replaced by 1 ELSEWHERE A 0 all the rest replaced by 0 END WHERE WRITE se
149. tion is not 5 4 15 14 The Fortran 90 intrinsic operator will n perform matrix multiplication The intrinsic operation A B where A and product of the two B are arrays represerting matrices retums an array with each element the simpl corresponding elements of A and B We will discuss below how to redefine the irtrinsic operetor to perform matrix multiplication But before we do this it is instructive to write a subroutine tomultiply two matrices directly SUBROUTINE MyMatMul A B C multiplies A n x m by B m x p and returns product in C n x p performs no checks on shapes of A and B REAL DIMENSION A B C INTEGER I J M N P N SIZE A 1 number of rows M SIZE A 2 number of columns P SIZE B 2 DO I 1 N DO J 1 P C I J SUM A I 1 M B 1 M J scalar product END DO END DO END SUBROUTINE MyMatMul explicitly with DOK 1 M C I J c END DO Note that the intrinsic function SIZE has an optional second argument specifying the dimension of which the size is required The statement which computes C I J illustretesthe use of Fortran 90 array sections A I 1 M isthe Ithrow of AandB 1 M J isthe Jth column of B Boththese sections are one dimensional The sum of their intrinsic product returns the scalar product of thet wo sections This could be done I J A I K B K J
150. truncated when irtegers are divided arwhen integers are assigned to reals e Numeric assignment computes the value of a numeric expression and assigns it to a real or irteger variable e Groups of variables may be given initial values ina DATA statement e PRINT is usedto pirt display otp e READ is used to input data from the keyboard while a program is running e Data may also be read from an external file g a disk file Chapter 2 Exercises 2 1 Evaluatethe following numeric expressions giventhat A 2 3 3 C 5 reals and I 2 J 3 irtecers Answers are given in parertheses A B C 11 0 A B C 16 0 B C A 1 2 B C A 0 3 A I J 0 333333 I J A 0 0 A B T A J 2 4 5 Cc B A 3 B 2 7 25 Bek Behe iE 512 0 By ee Ae Re IC 45 0 J I 3 division by zero 2 2 Decide which of the following constants are not written in tandard Fortran and state why not a 9 87 o 0 c 25 82 d 356231 e 3 57 E2 E 3 57E2 1 g 3 57E 2 H 3 57E 2 2 3 State giving reasons which of the following are nd Fortran variable names a A2 b A 2 c 2A d A ONE e AONI lka Hh x g MiXedUp h Pay Day i U S S R j Pay Day k min 2 1 PRINT 2 4 Find the values of the following expressions by writing short programs to evaluate them answers in parentheses
151. update existing file END IF B iS B FileStatus NEW it isn t there so create it END IF OPEN 1 FILE FileName STATUS FileStatus amp ACCESS DIRECT RECL ReclLen Ans make sure we get started DO WHILE Ans Q PRINT 159 PRINT A Add new records PRINT D Display all records PRINT QO Quit PRINT U Update existing records PRINT WRITE Enter option and press ENTER ADVANCE NO READ Ans SELECT CASE Ans CASE UA atty CALL AddRecords CASE DY dq CALL DisplayRecords CASE TU ww CALL UpDate END SELECT END DO CLOSE 1 CONTAINS SUBROUTINE AddRecords SUBROUTINE DisplayRecords SUBROUTINE ReadIntCon Num SUBROUTINE StripBlanks Str SUBROUTINE UpDate END The length of the component Name of StudentRecord is declared as a named constart NameLen because this value is used in a number of cther declaretions The basic variable in the program is Student of type StudentRecord An INQUIRI statement detemines its record length forthe subsequent OPEN statement Gl The user is asked for the file name of the database Ancther INQUIRE statement determines whether or not the file exists A value is s amp forthe STATUS specifier in the OPEN statement depending on whetherthe file isto be replaced updated or created after which the fileis opened If the value of ST
152. way the assignment N N 1 is meaningful and means increase the value of N by 1 whereas the mathematical equation n ntl is nct generally meaningful Tf expr is not ofthe same type as var itis convertedtothattype before assignment This means that there might be loss of precision For example assuming N is irteger and X and Y are real N 10 3 value of N is 3 MSOs of 33 value of X is 3 0 YS AO of BS value of Y is 3 33333 The danger of performing integer divisions inadvertently cannot be stressedtoo much For example you might want to average two marks which happen to be integers M1 and M2 The most natural statement to write is FINAL M1 M2 2 but this loses the decimal part of the average t is always safest to write constarts as reals if real arithmetic is what you wart FINAL M1 M2 2 0 Examples The formulae 10 may be translated irto the following Fortran assignments F G M x R 2 C A x B 2 0 5 f 2 A Fl x 2 17 A P 1 R 100 N The second can also be written withthe SQRT intrinsic function as C SQRT A 2 B 2 2 A but never as C E A RR 2 che Be OR De RK Def oft 2 lt oA 1 2 inthe exponent evaluates to zero because of irteger division 2 10 Simple Input and Output Inthis section we will look atthe READ and PRINT statements more closely The process of getting information into
153. we can speedthings up by restricting Pto odd numbers so we only havetotry odd divisors N When do we stoptesting When N P No we 69 can stop a l sooner In fact we can stop once N reaches V P since ifthere isa factor greaterthan vP there must be a corresponding one lessthan P which we would have found And where do we start Well since N 1 willbea factor of any P we should start at N 3 The structure plan is as follows L 2 3 Read P Initialize Nto 3 Find remainder R when P is divided by N until R Increase N Find R when P is divided by N R 0 1s Repeat If P Else P is n prime 6 Stop Note that the exit condi Note also that there are two condi ion is tested at the top of the loop because R might be zero the ions under which the loop will to Consequently an IF is or by first time required after completion of the loop to determine which condi ion stopped it Here s the program PROGRAM Prime Tests if an odd integer gt 3 is prime IMPLICIT NONE INTEGER N 3 INTEGER P Rem PRINT Gimme an odd integer READ P Rem MOD P N DO IF Rem OR N gt SQRT REAL P N N 4 2 Rem MOD P N END DO IF Rem 0 THEN PRINT P is prime ELSE PRINT P is not prime END IF END EXIT Try it out on the following 4 058 879 n pr
154. where J is an integer variable J and K are integer expressions and block stands for any number of statements The block is executed repeatedly the values of J and K determine how many repeats are made On the first loop J takes the value of J and is then increased by 1 at the end of each loop including the last Looping stops once J has reached the value of K and execution proceeds with the statement after END DO J will have the value K 1 after completion of the loop nomal exit You can probably guess how DO works in reverse Square rooting with Newton The square roct x of any positive number a may be found using only the arithmetic operations of addition subtraction and division with Newton s method This is an iterative repetitive procedure that refines an initial guess there are more general examples in Chapter 16 The structure plan of the algorithm to findthe square roc andthe program with sample output for a 2 is as follows 1 Inputa 25 2 Initialize xto 1 3 Repeat 6 times say Replace x by x a x 2 Prirk x 4 Stop PROGRAM Newton Square rooting with Newton IMPLICIT NONE REAL A number to be square rooted INTEGER I iteration counter REAL X approximate square root of A WRITE 10 ADVANCE NO Enter number to be square rooted 10 FORMAT
155. which has the form Ifthe last statement ahead of the CONTAINS statement does not resultin a branch and it should not control passes over the irternal subprograms to the END statement andthe program stops In other words the internal subprograms are only executed if properly invoked by a CALL statement in the case of a subroutine ar by referencing its name inthe case of a function 8 3 External Subprograms An external subprogram resides in a separate Al fromthe main program t will generally perform a specifictask andis external in orderto be accessibleto many different calling programs Apart from the header and END statement a subprogram is idertical in aopearance to amain program SUBROUTINE name arguments declaration statements executable statements CONTAINS internal subprograms END SUBROUTINE name or FUNCTION name arguments declaration statements executable statements CONTAINS internal subprograms END FUNCTION name 92 Note the smalLbut significart differences between external and irternal subprograms e external subprograms may themselves contain irternal subprograms which will only be accessible to the host external subprogram irternal subprograms may not contain further irternal subprograms e the keyword FUNCTION or SUBROUTINE is optional in the extemal subprogr
156. write your own functions to be usedinthe same way ina program Before we discuss the rules in cetail we will look a some examples Newton s method again Newton s method see also Chapter 16 may be usedto solve a general equation f x 0 by repeating the assignment f x f x x becomes x where f x isthe first derivative of f x until fix has come clase enough to zero 3 2 1 Suppose that J x x x 3 Then a x 3x The program below uses Newton s methodto solvethis equation starting with x 2 and stopping either when the absolute value of f x 6 islessthan 10 or after 20 iterations say Ik uses two functions F X for f x and DF X for fi PROGRAM Newton Solves f x 0 by Newton s method IMPLICIT NONE INTEGER Its 0 iteration counter INTEGER MaxiIts 20 maximum iterations LOGICAL Converged false convergence flag REAL Eps le 6 maximum error REAL sao x 2 starting guess DO WHILE NOT Converged AND Its lt MaxIts X X F X DF X PRINT X F X Its Its 1 87 Converged ABS F X lt Eps END DO IF Converged THEN PRINT Newton converged ELSE PRINT Newton diverged END IF CONTAINS FUNCTION F X problem is to solve f x 0 REAL F X F X 3 X 3 ND FUNCTION F el FUNCTION DF X first derivative
157. 0 09 andinsertinga new block of statements afterthe READ as follows IF OldBal lt 5000 THEN Rate 0 09 ELSE Rate 0 12 ENDIF Try this out with sensibly chosen data to verify that it works For example 4000 will grow to 4360 whereas 5000 will gow to 5600 3 2 Deciding with IF THEN ELSE We will discussthe IF THEN ELSE statement jut itroduced more fully inthis section As an example suppose that the final course mark of students attending a university course is calculated as follows Two examination papers are written at the end of the course The final mark is ither the average of the two papers orthe average of the two papers andthe class record mark all weighted equally whichever is the higher The following program computes and prints each student s mark withthe comment PASS orFAIL 50 being the pass mark PROGRAM Final Mark Final mark for course based on class record and exams IMPLICIT NONE REAL CRM Class record mark REAL ExmAvg average of two exam papers REAL Final final mark REAL P1 mark for first paper REAL P2 mark for second paper INTEGER Stu student counter OPEN 1 FILE MARKS PRINT CRM Exam Avg Final Mark PRINT DO Stu 1 3 READ 1 CRM P1 P2 ExmAvg Pl P2 2 0 IF ExmAvg gt CRM
158. 0 5m m hg x 0 5k y 0 5m k hf x k y m m hg x k y m It should be noted that in this example x and y are the dependent variables and t which does not appear explicitly in the equations is the independent variable In Equation 16 4 y is the dependent variable and x is the independent variable 16 6 A Differential Equation Modelling Package This section implements a skeleton interactive modelling program Driver Its basis is a fourth order Runge Kutta procedure to integrate a time based systen of any size of first order differential equations Tt consists of four program units which can be compiled separetely only one of which needs to be recompiled by users e a module DrGlobal with global c eclaretims of derived types and variables e an extemal subroutine DEqs which definesthe model differential equations in principle this isthe only program unit which needs to be recompiled when the user sets up or changes a model e a module DrUtils with same basic utility subroutines including a Runge Kutta subroutine e a main pogam Driver to nin the package 238 Each of these program units will be describedinturn To illustrete the package it is set up here to run the p and s 2 orpey model of Section 16 5 with x 0 105 y 0 8 p 0 4 q 0 04 r 0 02 DrGlo
159. 0 A 3 0011 3 11 1011 B 4 0100 4 12 1100 C 5 0101 5 13 1101 D 6 0110 amp 14 1170 iE T 0111 rd 15 1111 F A byte is the amount of computer memory required for one character and is eight bits long Since each bit in a byte can be in two possible states this gives 2 i e 256 different combinations Hexadecimal code see table is often used because it is more economical than binary Each hexadecimal digit stands for a power of 16 E g f x x x 3 One byte can be represented by two hex digits Microcomputer memory size and disk capacity is measured in bytes so 64K for example means slightly more than 64 000 bytes since 1K actually means 1024 Microcomputers are sometimes referred to as 8 16 or 32 bit machines This describes the length of the units of information handled by their microprocessors chips The longer these units the faster the computer Integer literal constants Integer literal constants are usedto dencte the values of the integer irtrinsictype The simplest and most obvious representation is an unsigned or signed irteger whole number eg 1000 O 753 999999 2501 Inthe case of a positive irteger constant the sign is octional The range of the integers is not specified in the standard but on a 16 bit computer for example Nx 3x2 6 could be from 32768 to 32767 ie f 3x 1 10 The range may be spec
160. 00 15003 36 5OKKKKKKKKKK Euler 49 49 313 00 OO KKKKKKKKK on t Time OV O EO OO 2 00 JOT 02 03 04 05 lt 10 20 00 00 42 36 32 29 27 19 12 Sa 54 Euler 49 49 24 99 98 81 29 30 69 98 72 20 13 4 6 Dis Euler s method in general Exact 49 Te 49 62 6 02 5 5 43 77 Exact 49 43 38 34 SHR 28 49 18 31 45 31 71 43 32 02 Ld ution show that the man flies upward he does so with tremendous speed The results make nonsense physically Fortunately in this lis us that something is wrong The only remedy is to reduce h Some that the results forh 0 01 are much better 2 Euler s method willbe just as easy to compute ifthe airresistanceterm isnot kv 18 kv which ismore realistic although now an analytic solution cannot be found In general we want to solve a first order differential equation of the form dy dx f x y YO given Table 16 1 Bacteria growth Time Euler Predictor Corrector Exact 0 1 1000 1000 1000 05 1400 1480 1492 10 1960 2190 2226 15 2744 3242 3320 20 3842 4798 4953 50 28925 50422 54598 8 0 217795 529892 601845 10 0 836683 2542344 2980958 Euler s method replaces dy dx by its Newton quotient so the differential equation becomes 235 y x h y x h Rearranging we get f x y Vas
161. 1 P X 0 with similar notation forthe othertwo age classes W ion from month fto month t 1 as follows We now defire a population vector X t withthree components X 9 A x and X 1 cepresenting the three age classes ofthe rabbit population in morth The above three equations can then be rewritten as 213 x 0 F R x X P 0 Ox xX X Jian 0 P 0 X where the subscrig at the bottom of the vectors indicaesthe month We can write this even more concisely as the matrix equation X 1 LX where L isthe matrix 0 9 12 1 3 0O 0 0 1 2 0 inthis particular case L is called a Leslie matrix A population model can always be written inthe form of Equation 15 4 ifthe concerts of age classes fertility and survival factors as outlined above are used Now that we have establisheda matrix representation for our model we can easily writea program using matrix multiplication and repeated application of Equation 15 4 X t 2 LX t 1 X t 3 LX 2 amp c However we only need a single one dimensional array X inthe program because repeated matrix multiplication by the two dimensional array L will continually update it X L x X using the x matrix multiplication operator defined in module MatMult We will assume to coe wie aus A E aad Es ae eget Oe Th
162. 1 the lowest value a subscript cantake However you can have any lower bound you Like REAL DIMENSION 0 100 A declares Ato have 101 elemerts from A 0 toA 100 The upper bound must be specified ifthe lower bound is missing it defaultsto 1 An array may have more than one dimension The bounds of each dimension must be specified REAL DIMENSION 2 3 A 110 A is atwo dimensional array The number of elements along a dimension is calledthe extent in that dimension A has an extert of 2 inthe first dimension and an exter anda size of 6 Fortran allows upto seven dimensions The number rank andthe sequence of extents isits shape The shape of Ais 2 3 t of 3 inthe second dimension of dimensions of an array is its or 2x3 in matrix notation A scalaris regarded as having a rank of zero We will concentrate mainl y on one dimensional arrays in this chapter it is more appropriate to discuss two dimensional arrays in the context of matrices Chapter 14 The DIMENSION attribute is optional t provides a default DIMENSION optionalshape for variables whose names are not followed by a shape REA INT DIMENSION 5 ER I 10 K 4 4 A B 2 3 C 10 5 i only A is 1 5 all different 17 EG An array subscrig can be used as the control variable in a DO loop to generate array elements Th
163. 1 0 N remember integer division IF MOD N 10 0 PRINT Sum END DO INTEGER Secs Mins Hours READ Secs Hours Secs 3600 Secs MOD Secs 3600 number of seconds over Mins Secs 60 Secs MOD Secs 60 PRINT Hours Mins Secs Chapter 5 oye REAL A B READ A B IF A gt B THEN PRINT A is larger ELSE IF B gt A THEN PRINT B is larger H iS E PRINT number are equal END IF 5 2 1 Repeat 10 times Read number If number lt 0 then increase negative courter otherwise if number 0 then increase Zero counter otherwise increase positive counter 2 Print courters 278 INTEGER I Num NPos NZer NNeg NPos 0 NZer 0 NNeg 0 DO I 1 10 SELECT CASE Num CASE 1 NNeg NNeg 1 CASE 0 NZer NZer 1 CASE DEFAUL iT NPos END SEL END DO PRINT ECT NNeg 5 5 1 Read a b c d e f 2 u ae db v ec bf 3 716 u Lines Otherwise Lines Otherwise x Prit y if 4 Stop a Ee A F RINT x END IF Chapter 6 INT REA Pi DO X Ang PRINT END DO EGER X Ang Pi 4 ATAN 0 90 KNB I3 REAL Bal INTEG Bal 1000 Rate 0 01 DO Year 1 DO Month Bal END DO PRINT DO Rat ER Month e
164. 10 and e 1 gives x 9 42 x 10 with FTN90 However the second roct may also be expressed mathematically as e e a Ja e 2a X2 Using this fom with FTN90 gives x 10 7 which is more accurate Rounding error is also discussed in Chapter 16 Chapter 7 Summary e Compilation errors are mistakes in the syrtax coding e Execution run time errors occur while the program is running e Input output eros may be irtercepted at run time e Debugging facilities may be usedto work through a program statement by statement e Logical errors are errors in the algorithm used to salve the problem e Rounding error occurs because the computer can store numbers only to a finite accuracy tis reduced but not necessarily eliminated by using reals with higher precision than the default Chapter 7 Exercises 7 1 The Newton quotient f x h f x h may be usedto estimatethe first derivative f x of afunctim f x ifhis small Write a program to compute the Newton quotient forthe function f x x atthe point x 2 the exact answer is 4 for values of h starting at 1 and decreasing by a factor of 10 each time The effect of rounding error becomes apparent when h gets too small i e less than about 10 7 2 The solution of the set of simultaneous equations ax by c dx ey f Exercise 5 5 is given by x ce bf
165. 27 0 5 real division real division in exponent E AS S 5 AA TO K3 d xx 2 2 OR SPAR ERED 1000 1 0 15 12 k k 60 goes from right to left by default 10 LL LS 14 215 X X 3 2 3 X 5 2 3 4 5 I 2 30 1 2 30 BAL Ay By Cy xX EAD A B C B B 2SM RAKE RE OLS A 250 A RINT X Hux o Zz iw EAL G P L RINT Enter gallons and pints EFAD G P 8 G P P 1 76 RINT L litres un UD w E Z iw IMPLICIT NONE REAL Km L Km L L_100Km Km 528 L 46 23 Km L Km L L 100Km L Km 100 PRINT Distance Litres used Km L L 100Km PRINT PRINT Km L Km l L_100Km END THA A B B T A A B B BtaA A B A REAL L P R INTEGER N L 50000 PRINT Enter N and R as a decimal READ N R P R L 1 R 12 12 N P P 12 1 R 12 12 N 1 PRINT Monthly payment P END REAL L N R P PRINT Capital amount monthly payment interest rate READ L P R N LOG P P R L 12 N N 12 LOG 1 R 12 PRINT Repayment period in years months N 12 N END REAL PARAMETER Pi 3 1415927 REAL C E I Il L R Omega R 5 C 10 L 4 E 2 Omega 2 Il 2 Pi Omega L 1 2 Pi Omega C T E R 2 T1 2 0 5 PRIN
166. 5 INTEGER RecNum INTEGER KeyField END TYPE Key TYPE StudentRecord CHARACTER NameLen Name INTEGER Mark END TYPE StudentRecord TYPE Key KeyVar TYPE KEY DIMENSION MaxStu KeyArr TYPE StudentRecord Student INTEGER EOF Num RecNo TotRecs INTEGER KeyLen StuLen INTEGER KeyFile 1 unit for key file INTEGER StuRecFile 2 unit for StudentRecord file INQUIRE IOLENGTH StuLen Student OPEN StuRecFile FILE student rec STATUS OLD amp ACCESS DIRECT RECL Stulen INQUIRE IOLENGTH KeyLen KeyVar OPEN KeyFile FILE marks key STATUS REPLACE amp ACCESS DIRECT RECL KeylLen RecNo 0 create the key fil EOF 0 DO WHILE EOF 0 READ StuRecFile REC RecNot l IOSTAT EOF Student IF EOF 0 THEN RecNo RecNo 1 total number of records KeyVar RecNum RecNo KeyVar KeyField Student Mark WRITE KeyFile REC RecNo KeyVar KeyArr RecNo KeyVar and copy into array END IF END DO TotRecs RecNo total number of records CALL Key Sort KeyArr TotRecs DO Num 1 TotRecs write sorted array back to key file WRITE KeyFile REC Num KeyArr Num END DO PRINT Order of merit using th
167. 6 8 4 Write a subroutine QUAD X1 X2 A B C J REAL INTENT OUT X1 X2 REAL INTENT IN A B C INTEGER INTENT OUT J which computes the rocs of the quadratic equation ax bx c 0 The argumerts A B and C which may take any values are the coefficients of the quadratic and X1 X2 arethetwo rocts if they exist which may be equal See Figure 4 5 forthe structure plan Jisa flag which must be set by the procedure as follows 1 complex rocts discriminart lt 0 0 no solution a b 0 0 1 one rot a 0 b 0 sothe rox is c b 2s two rocts which could be equal 99 any xisasolttio b c 0 8 5 Ifarandom variable Xis distributed normally with zero mean and unit standard deviation the D x probability that On X Sx is given by the standard normal function This is usuallylooked up intables but it may be approximated as follows x 0 5 rat bt ct p exp 0 5x7 J2 where a 0 4361836 b 0 1201676 c 0 937298 and t 1 1 03326x Write a function to compute o x and use itin a program to write out its values for 0 Sx 4in steps of 0 1 Check 1 0 3413 8 6 The Fibonacci numbers are generated by the sequence Vy Ty 235 EE pss 106 mis W ritea recursive function F N to computethe Fibonacci Can you work out what the next ter Fy to Fy using
168. 99 These conventions will nct necessarily work on a dot matrix printer connectedto a PC However a combination of OPEN and WRITE withthe CHAR intrinsic function can be used to send any special control characters to the printer The following code sends a form feed character new page EN 1 FILE prn WRITE 1 10 CHAR 12 10 FORMAT Al The contral characteris not restrictedtothe firt position inthe output record it can be anywhere In this way you can send any of your prirter s gcecial prirting codes 10 4 Formatted READ The form of the READ statement we have used so far is READ fint list where fmt is a label asterisk or character string as in PRINT There is a more general form which allows input from files and which can intercept errors and end of file conditions gracefully without causing the program to crash Eis READ UNIT u FMT fnt IOSTAT ios ERR errorlabel END endlabel list The only obligatory items are the format specifier fmt as described above and the unit specifier u A unit is an I O device such as a prirtey terminal or disk drive for example which may be connected by the compiler to your program Such a unit may have a unit number attached to it which is usually inthe range 1 99 forthe duration of a prog
169. A 1 rows of A DO J 1 SIZE B 2 columns of MatTimesMat I J Elt SUM A B 1 EM J Elt END DO END DO END FUNCTION MatTimes A B T E B 2 MatTimesMat columns of A must equal rows of B B I 1 EM Elt amp scalar product 9 O he oper tor can then be overloaded with an irtert FUNCTION REAL X TYPE MATRIX TYPE MATRIX SIZE B 2 ScalarTimesMat X B DIMENSION DIMENSION SIZI ScalarTimesMa B B 1 Gl GI F py o CI 206 Multiplication of a scalar by a matrix can be defined by a si face block as above ilar function say amp to handle expressions like 2 B where the operands are represerted by the arguments in that order If you also wart to be able to write B 2 you would need athird function say FUNCTION MatTimesScalar A X REAL X TYPE MATRIX DIMENSION A TYPE MATRIX DIMENSION SIZE A 1 amp SIZE A 2 MatTimesScalar The interface block wouldthen look likethis the functions must all be inthe same module INTERFACE OPERATOR MODULE PROCEDURE MatTimesMat ScalarTimesMat MatTimesScalar ND INTERFACE m TE might also be conveniert to redefine the assignment operator to allow statements like A 0 This must be done with a subroutine where the two arguments represent
170. AL A number of cases READ T A 174 6 T 1981 2 3 PRINT Accumulated AIDS cases in US by year T A END PROGRAM AIDS Tf you supply the value 2000 forthe year you should get the output Accumulated AIDS cases in US by year 2000 1 1601688E 06 6 The answer is given in scientific notation E 06 means multiply the preceding number by 10 r SO the number of cases is about 1 16 million Using trial and error run the program repeatedly to find out when there will be about 10 million accumulated cases Try typing a mistake in the valve of 2 000 for example to see how Fortran responds Compound interest Suppose you have 1000 saved inthe bank which compounds interest atthe rate of 9 per year What will your bank balance be after one year You must obviously be ableto do the problem in principle yourself if you wantto program the computerto do it The logical breakdown or structure plan of the problem is as follows 1 Get the data initial balance and interest rete irto the computer 2 Calculate the interest 9 of 1000 Le 90 3 Add the irterest to the balance 90 1000 ie 1090 4 Prirt display the new balance This is how the program looks PROGRAM MONEY Calculates balance after interest compounded REAL BALANCE INTEREST RATE BALANCE 1000 RATE 0 09 INTEREST RATE BALANCE BALANCE BALANCE INTEREST PR
171. AT 13F6 0 CALL Quick Sort List 1 N quick sort now PRINT 10 List print sorted list CONTAINS RECURSIVE SUBROUTINE Quick Sort X L R REAL DIMENSION INTENT INOUT X jist INTEGER INTENT IN L R left right bounds INTEGER L1 R1 etc IF L lt R THEN Ll L R1 R DO DO WHILE L1 lt R and X L1 lt X L shift L1 right L1 L1 1 END DO DO WHILE L lt R1 and X R1 gt X L shift R1 left R1 R1 1 END DO IF L1 lt R1 CALL Swop X L1 X R1 swop IF L1 gt R1 EXIT crossover partition END DO CALL Swop X L X R1 partition with X L at R1 CALL Quick_Sort X L R1 1 now attack left subproblem CALL Quick Sort X R1 1 R don t forget right subproblem END IF END SUBROUTINE Quick Sort 118 SUBROUTINE Swop A B REAL INTENT INOUT A B REAL Temp Temp A A B Temp w E END SUBROUTINE Swop m 2 o the sample array in the figures Note that the swopping is implemented as a subroutine If you rewrite Quick_Sort as an external subroutine Swop could be intemaltoit You shouldtry workingthrough the program by hand with Try the Quick Sort out on 1000 numbers You should be impressed Tt has been provedthat Quick Sort needs approximately Nlog comparisons as opposed to the Bubble Sort s N 2 You may be interesttedto leam that Quick Sort slows down tremendously ifthe list is
172. ATUS has been correctly set the OPEN must succeed otherwise you needto cater for error recovery with the IOSTAT and or ERR specifiers Next a menu is preserted The ideal construct forthisisDO WHILE The user enters a single letter response A CASE construct selects the appropriate subroutine An importart point to note here is that the response may be in lower or uppercase Since other responses will be required in th program it makes senseto write a function to convert the response to uppercase say before testing at Ithied to include such a function FUNCTION ChToUpper Ch converts a single lowercase character to uppercase leaves all other characters unchanged CHARACTER Ch ChToUpper ChToUpper Ch SELECT CASE Ch CASE a s z2 ChToUpper CHAR ICHAR Ch ICHAR A ICHAR a END SELECT ND FUNCTION ChToUpper El but a bug inthe FTN90 compiler caused a run time error when it was included in the database program although it ran successfully on itsown in atest program 160 When the user quits the database file is closed Now forthe subroutines AddRecords adds new records either at the end of an existing database or at the beginning of a new one SUBROUTINE AddRecords RecNo 0 EOF 0 remember to initializ
173. BROUTINE DEqs END INTERFACE CONTAINS SUBROUTINE Headings INTEGER I PRINT 3A11 Time PRINT PRINT 3F11 2 T X END SUBROUTINE Headings SUBROUTINE Initialize All NumVars 2 NumParams 4 ALLOCATE Vars NumVars Vars 1 Name Prey Vars 1 InVal 105 Vars 2 Name Pred Vars 2 InVal 8 Params 1 Val 0 4 Params 2 Val 0 04 Params 3 Val 0 02 Params 4 Val 2 0 Vars Val 0 dt 1 T 0 RunTime 10 END SUBROUTINE Initialize SUBROUTINE Run CALL Headings DO Itime 1 RunTime T T dt CALL Runge PRINT 3F11 2 T X END DO Vars Val X END SUBROUTINE Run SUBROUTINE Runge 4th order Runge Kutta REAL F NumVars REAL DIMENSION NumVars REAL h A 0 B 0 C 0 D V X 240 Vars I 5 Params NumParams Gl n defines model DI generates output headings Name I 1 NumVars this info could be read from a disk file X NumVars set current values to zero for safety run the model current values A B C D V working space initialize initialize for Runge Kutta 2 ee Avot 2 Bits 2 Cote D UTINE Runge m z BROUTINE TidyUp close files DEALLOCATE Vars D SUBROUTIN Params X m 2 F py END MODULI Utils Gl Dr Ir Headings generates headings forthe output E throw away dynamic storage
174. CONTAINS RECURSIVE FUNCTION Factorial N INTEGER Fact N IF N 1 THEN Fact 1 ELSE Fact N Factorial N 1 END IF END FUNCTION END RESULT Fact name forthe function This isillustreted below wherethe function Factorial is The RESULT clause is needed becausethe name Factorial may not appear on the left hand side of an assignment Notethatthe name Factorial must not be declaredin the INT the cdeclaretion of Fact is sufi ficient T iG ER statement Recursion is an advanced topic although it appears deceptively simple You may wonder how the recursive Factorial function really works It is importart to distinguish between the function being called and executed When the initial call takes place N has the value 10 sothe E iS E Clause in Factorial is evaluated However the value of Factorial 9 isnot known at this stage so a copy is made of allthe stetements inthe function which will needto be executed oncethe value of Factorial 9 is known The referenceto Factorial 9 makes Factorial callitsel time witha value of 9 for N Againthe ELS E thi E clause is evaluated and again Fortran 90 discoversthat 103 it doesn t know the value of Factorial 8 So another differert copy is made of all the statements that will need to be executed oncethe value of Factorial 8 is known And so ea
175. Check Hand C NS H PRINT m ND DO CONTAINS FUNCTION INTEGE Ranint D FUNC D m m N N A different REAL R Count DOM SEED Put Seed L723 deal 13 cards RanInt LE Check Num 0 already dealt RanInt o so try again Num 1 tick it off ard Num and Card 13 NV MOD Hand Card 13 3A T20 315 Value NV of Suit NS amp Hand Card NS NV RanInt R Ranint CALL RANDOM NUMBER R INT 52 R TION RaniInt hand will be dealt every time the program is run Here is a sample hand headings have been inserted into the text for clarity Hand NS Six of Jack of Queen of Nine of Three of Two of Five of Three of Ace of Eight of Six of Ten of Six of 192 NV Clubs 43 3 4 Spades 9 0 9 Clubs 49 3 10 Diamonds 33 2 7 Diamonds 27 2 1 Clubs 39 3 0 Clubs 42 3 3 Clubs 40 3 al Clubs 51 3 12 Diamonds 32 2 6 Hearts 17 alt 4 Hearts 2L 1 8 Spades 4 0 4 You may feelthat the method of shufi because as more cards are dealt so the number o following code segment shut fling the cards withthe DO WHILI E loop is very ineff ficient f calls to RANDOM NUMB ER goes up The EF es all 52 cards by starting w ith a sorted pack by i nitializing Hand and swopping them at rando
176. Current is only null afterthe last execution of the loop when itis made an alias of the pointer in the first node This process demonstrates how important itis to have the pointer L pointing to the nd of the liss otherwise you could never find it One of the advantages of using a linked list is that it can be disposed of when no longer needed releasing valuable memory This may be done as we traversethe lit from the end although now a little more housekeeping is required Taa Once again make Current an alias of the end of the lig Current gt L You might be temptedto deallocate Current straight away However if you look at Figure 13 1 you will seethatthisis a prescriction for disaster Withthe lat node removed the link tothe second 180 last one is broken and it consequently can never be found So before deallocating Current the end marker L should be made to poirt to the second last node L gt Current Next Now Current may be safely deallocated and the general node Current made an alias forthe new end of the lit Current gt L This process must be carried out as long as the end marker L is n null PRINT Deleting Current gt L make Current alias of last node again DO WHILE ASSOCIATED L L gt Current Next disconnect L from last node and make it l point to next one instea
177. D 2 logical irtersection OR 3 logical union EQV and NEOV 4 logical equivalence and non equivalence The following truth table shows the effects of these operators on the logical expressions lex and lex2 T true F false lex1 lex2 NOT lex1 lex1 AND lex2 lex OR lex2 lexi EQV lex2 lex1 NEQV lex2 F F T T E F E F HAA tj F F ak F The order of precedence shown above may be superseded with parertheses which always have the highest precedence Examples B B 4 A C AND A 0 Final gt 60 AND Final lt 70 AAE 0 wor B 0 cof C 0 enot A 0 and B 0 and C 0 Incidentally the last two expressions are equivalert and are false only when A B C 0 it makes you think doesn t it 52 Logical variables A variable may be declared with logical type in a LOGICAL statement Logical constants or expressions may be assigned to logical variables Figure 5 1 Switching circuits Series Parallel OGICAL Ll L2 L3 L4 L5 REAL A B C Ll TRUE L2 B B 4 A C gt 0 L3 A 0 L4 Ll and not L2 or L3 L5 L1 and not L2 or L3 The precedence rules make L4 and L5 logically equivalert The truth values of logical variables are represented by T and F in lit directed I O Simulation of a switching circuit In the following prog
178. D PROGRAM GaussTest mm Note that the two statements A PivRow 1 N 1 A PivRow 1 N 1 PivElt divide whole row A TarRow 1 N 1 A TarRow 1 N 1 amp A PivRow 1 N 1 TarElt process entire rows If you do a lct of numerical analysis you will appreciate the power of such Fortran 90 array expressions Unfortunately things can go wrong with our subroutine 1 The pivct element could be zero This happens quite easily when the coefficierts are all irtegers However rows of the array can be interchanged see below without changing the system of equations So a non zero pivot element can often be found in this way but see the next two cases 2 A row of zeros could appear right across the array in which case a non zero pivct element cannct be found Inthis case the system of equations is indeterminate andthe solution can only be determined down to as many arbitrary constants as there are rows of zeros 3 A row ofthe array could be filled with zeros except forthe extreme right hand element In this case the equations are inconsistert which means there are no solutions Eisa nice programming prot to extend the subroutine Gauss to deal with these three cases Matrix inversion by Gauss reduction 219 Consider the system of equations 2x 2y 2z 0 3x 2y 2z il 3x 2y 3z 1 Tf we define the matrix A as Ae WwW WN N NDN w
179. DIMENSION 5 5 A C X Y both rank one with same size 121 Y full of zeroes j X 1 xX replac ach element of X with its reciprocal X COS X replac ach element of X with its cosine X 1 5 Y 4 8 both rank one with size 5 A I 1 J C K 1 J row K of matrix C assigned to row I of j matrix A These facilities are extremely useful in numerical procedures such as Gauss reduction Tf the expression on the right of an array assignment refers to part of the array on the left the expression is filly evaluated before the assignment begins E g X 1 3 K 2 4 results in each element of X I I 1 2 3 having the value that X I 1 had before the assignment began The WHERE construct W HEREconstuuct may be used to perform an operation on only certain elements of an array e g WHERE A gt 0 A LOG A log of all positive elements ELSEWHERE A 0 all non positiv lements set to zero END WHERE The ELSEWHERE clause is optional The construct is analogous to IF THEN ELSE The expression in parentheses after the keyword WHERE is a logical array expression and may simply be a logical array Ik issometimes called a mask There is a comesponding WHERE statement WHERE A 0 A 1 A replace non zero elemerts by reciprocals Array valued fun
180. DO WHILE IO 1 check for EOF READ 1 Al IOSTAT IO ADVANCE NO Ch IF IO 0 THEN protect against EOR and EOF IF Ch BL AND OldCh BL THEN arrival of blank WORDS WORDS 1 l signals end of word PRINT new line ELSE IF INDEX LETTER Ch 0 THEN Ch must be a letter WRITE Al ADVANCE NO Ch part of word END IF OldCh Ch END IF END DO IF OldCh BL THEN if last char actually read is non blank WORDS WORDS 1 count another word PRINT new line END IF PRINT PRINT No of words WORDS END 146 11 6 General Information Character substrings Suppose the following character variable has been declared CHARACTER 80 TEXT Individual characters in TEXT may be referenced using a substring notation e g TEXT I J references a substring of TEXT from the Ith charactertothe Jth one If I is greater than J the substring is empty The colon is obligatory ht there are default values of the sulbscritts e g TEXT J same as TEXT 1 J TEXT J same as TEXT J 80 TEXT same as TEXT 1 80 or TEXT A substring may be formed from a character constart e g NAPOLEON 3 6 returns POLE Following are some examples of substring expressions and assignments TEXT abcdefghijk TEXT 1 3 XY returns XY defghijk blank at 3rd position TEXT 5 5 returns XY d fghijk replaces 5th
181. E NOD T TYPE LIST PRIVATE TYPE NODE POINTER End END TYPE LIST CONTAINS SUBROUTINE Dispose L TYPE NODE POINTER Current 181 TYPE LIST j Current gt L End DO WHILE ASSOCIATED End 6 End gt Current Next PRINT Current Value DEALLOCATE Current Current gt L End END DO ND SUBROUTINE a Dispose SUBROUTINE Insert TYPE NODE POINTER TYPE LIST INTEGER Num ALLOCATE Current Value Num Current Next gt L End gt Current END SUBROUTINE Insert Num Current Ly rrent End L Current cintList POINTER T the end now rom the end gt L End ASSOCIATED Current PRINT Current Value Current Next PrintList ROUTINE INE SetUp L IST L ROUTINE End Setup E END MODULE ModLink updat is about to go start at the end th nd befor disposing alias of last node again new node point it to previous node update the end of the list alias of last node alias of next node list is empty at first linked lig is now specified with a derived type The most i
182. EAL KIND P R kind parameter for a real data type with decimal precision at least P and decimal exponent range at leat R as retumed by PRECISION and RANGE At least one of the scalarintegers P and R must be present unavailable ifthe range is unavailable and if neither are available C 13 Transfer Function TRANSFER SOURCE MOLD SIZE same physical reo lisreturned ifthe precision is ion as SOURCE but type of fAcient to hold all of SOURCE MOLD Scalarif MOLD is scalar otherwise of rank one and size just sul If SIZE is present result is of rank one and size SIZE C 14 Non elemental Intrinsic Subroutines See Random numbers and Real time clock Random numbers Pseudo random numbers are generated fran a seed heldas a rank one integer array RANDOM NUMBER returns the random numbers and RANDOM_SE T D allows inquiries about the seed array and the seed to ke reset CALL RANDOM NUMBER HARVEST random number x uniformly distributed in the range O lt x lt l or an array of such numbers in HARVEST which has irtent OUT and must be real CALL RANDOM SEED SIZE PUT GET e SIZE scalar integer has irtert OUT and is s amp by the system tothe size N of the seed aray e PUT rankore irteger array size N has irtent IN and is used by t
183. EDURE MatTimesMat MatTimesVector ND INTERFACE m CONTAINS FUNCTION MatTimesMat A B REAL DIMENSION A B REAL DIMENSION SIZE A 1 SIZE B 2 MatTimesMat MatTimesMat MATMUL A B a END FUNCTION MatTimesMat FUNCTION MatTimesVector A X REAL DIMENSION A REAL DIMENSION REX REAL DIMENSION SIZE A 1 MatTimesVector MatTimesVector MATMUL A X END FUNCTION MatTimesVector END MODULE MatMult number of rows and columns for multiplication The function Mat TimesMat returns the matrix resulting fromthe multiplication of itstwo matrix arguments using the intrinsic function MATMUL Note that since Mat TimesMat cannot reun an assumed shape array unless it hasthe POINTER attribute it must be declared withthe dimensions of its arguments which are obtained at runtime We shouldstrictly check that A and B have the right 205 MatTimesVector is similar except that i however that the intrinsic function MATMUI t handles multipli L can handle both ion of a matrix by a vector Note these situations Since a vector is simply a one dimensional matrix the definition of matrix multiplication given above also applies in this case e g 1 2 2 8 3 4 13 18 A multiplication operetor x is d inter
184. F String I I gt a AND String I I String I I CHAR ICHAR String I I END IF END DO END SUBROUTINE END character dummy argument in a subprogra lt z THEN IBIG Ismall Note that an individual character may be referenced as a substring String I I1 andthata m may be declared with an asterisk to have an assumed length The irtrinsic function LEN returns the actual length of the argument The Bubble Sort o f Chapter 9 can easily be amendedto sort words alphabetically Suppose we have up to 100 words each of 10 leters or less they can be read from a text file List must now be declared inthe main program as follows CHARACTER 10 DIMENSION 100 List The corresponding dummy argument inthe subroutine BUBBLE SORT must be declared as CHARACTER The variable TI DIMENSION INTENT INOUT EMP inthe subroutine must be declared CHARACT X ER 10 altematively it could be passed as an argument and declared with an assumed length Finally you should incorporate ToUpper ifthe words will ke of mixed case Note incicertal ly that blanks in words are significart so that Mc Bean lt McBean since the blank precedes the letters 11 4 Graphs Without Graphics The following example shows how easily a simple graph can be drawn on the text screen it could to a file orthe prirter t makes use of an i
185. HHH p rs s ss os on on on nu ee tt HH HHHH The output is shown in Figure 15 2 Note thatthe x and y axes are also drawn We need now to discuss the module beginning with the mathematics required to transform the general poirt y irto a position on the screen or prirter The platting is done essentially by printing a two dimensional charader array Point in Grapher wherethe y co ordinate istransformedto row R andthe x co ordinate is transformed to column C A plating symbolisthen storedin Point R C Notethat the y co ordinate is represented by the first subscrig in keeping with the usual row column notation To be more precise the elemert Y T Vi ofthe array Y must betransformedto R Since we want a linear transformation we must have R ay b 15 1 where the constarts a and b must be determined Let s callthe highest poirt on the graph Yu This is set by the argument Ymax of SetWindow and must be transformed irto row 1 the top of the graph so l ay 6b 15 2 The lowest point on the graph Yo set by Ymin must be transformed irtothe maximum row Ry st in GraphMod by the constart MaxRow so R 4Yp b 15 3 Subtracting Equation 15 2 from Equation 15 3 immediately gives a R 1 _ yu and substituting back irto Equation 15 2 gives b l yy R 1 yp yu These values for a and b may be used in Equation 15
186. I N trBin M StrBin number of binary digits trBi n 80I1 Bin reads first N digits x DD N T 283 11 5 PROGRAM Upper CHARACTER 1 ch INTEGER IOEnd 0 OPEN 1 FILE TEXT DO WHILE IOEnd 1 for EOF under FTN90 READ 1 Al IOSTAT IOEnd ADVANCE NO ch IF ch gt a AND ch lt z THEN ch ACHAR IACHAR ch 32 ASCII codes END IF WRITE A1 ADVANCE NO ch IF IOEnd 2 PRINT for EOR under FTN90 END DO CLOSE 1 END 11 12 FUNCTION TIS REAL TIS INTEGER TIMES 8 CALL DATE AND S 5 TIME VALUES TIMES PRINT TIM TIS TIMES 3600 TIMES 6 60 TIMES 7 amp TIMES 8 1000 0 END FUNCTION TIS Chapter 13 F Ey Sty INTEGER POINTE INTEGER TARGET I J T 1 J 2 Pl gt I P2 gt J PRINT Pl P2 Temp gt Pl Pl gt P2 P2 gt Temp PRINT P1 P2 check where they point now Chapter 14 14 1 PROGRAM Bingo INTEGER Bing 99 I Temp Seed 1 Count R REAL Rnd CALL SYSTEM CLOCK Count Seed Count CALL RANDOM S ED PUT Seed Bing I I 1 99 DO I 1 99 CALL RANDOM NUMBE R INT 99 Rnd Temp Bing R Bing R Bing I Bing I Temp T
187. I H and Fu ung with an array Values 0 N say References to ng B would have to be changed to Values 0 Values I and Values N respectively Intrinsic functions as arguments Trap can be usedto irtegretean intrinsic function which must then be declaredinan INTRINSIC statement E g to irtegrate sine insert the statement INTRINSIC SIN irto Test Trap and change the call to 230 Trap PRINT Integral F8 4 Trap A B H SIN Simpson s Rule Simpson s rule is a method of numerical integration whichis a good deal more accurate than thr Trapezoidal Rule and shouldal ways be used before you try anything fancier Tr also dividesthe area under the function to be integrated f x ito vertical strips but instead of jaining the points S with straight lines every set of three such successive points are fi with a parabola To nsure that there are always an even number of panels the steo length n is usually chosen so that n b a 2h there are 2n panels Le Using the same notation as above Simpson s rule estimates the irtegral as A re 10 25 04 435 000 The coding for this formula which can be included inthemodule NumUtils is FUNCTION Simp A B H Fung REAL INTENT IN A B H REAL Simp INTEGER I N INTERFACE FUNCTION Fung X REAL Fung REAL INTENT IN X
188. INT New balance BALANCE END PROGRAM MONEY Run the program and nctethat no input f the keyboard is required now why not The output should be 1 0900000E 03 1090 Summary e A computer program is a set of coded instructions for salving a particular problem e The Fortran statement READ is for getting data irto the computer e The Fortran statement PRINT is for parting displaying results Chapter 1 Exercises 1 1 Writea programto compute and prirtthe sum difference product and quotiert of two numbers A and B supplied from the keyboard The symbols for subtraction and division are and respectively Use the program to discover how Fortran reacts to an attempted division by zero 2 1 2 The energy stored on a condenseris CV 1 2 where Cisthe capacitance and V isthe potential difference Write a program to compute the energy for some sample values of C and V Solutions to most exercises are in Appendix E Chapter 2 Elementary Fortran I Chapter 2 Introduction 2 1 Compound Interest Again 2 2 Program Layout e Statements e Significance of blanks e Comments e Continuation lines 2 3 Data Types 2 4 Literal Constants e Bits n bytes e Irteger literal constants e Real literal constants 2 5 Names and Variables e 6 Implicit type mle 2 6 Vert
189. IT NON REAL A B GI READ A B CALL SWOP A B PRINT A B CONTAINS SUBROUTINE SWOP X Y REAL Temp X Y Temp X me AS Y Temp END SUBROUTINE D T zal Z 91 What actually happens is that the actual arguments A and B are passed by reference see Section 8 7 The effect is that the values of the actual arguments are giventothe dummy arguments and any changes made tothe dummy arguments are copied back to the actual arguments In this way information can be returned from the subroutine This can have unpleasant side effects You might inadvertently change a dummy argument insice a subprogram after return to the calling program the corresponding actual argument will also be changed perhaps with disastrous effects Fortran 90 has a way of preventing this called argument intent which is discussed in Section 8 7 Since Temp inthe example above is declared inthe subroutine it is local to it and not accessible to the main program The general syntax of an intemal subroutine is therefore SUBROUTINE Name argument list declaration statements executable statements 8 2 The Main Program PROGRAM name declaration statements executable statements CONTAINS internal subprograms END PROGRAM name END SUBROUTINE Name Every complete program must have one and only one main program
190. Introduction to Fortran 90 for Scientists and Engineers Indice Cap 1 Getting Going 5 Cap 2 Chapter 2 Elementary Fortran I 8 Cap 3 Chapter 3 Elementary Fortran II 24 Cap 4 Chapter 4 Program Preparation 41 Cap 5 Chapter 5 Decisions 47 Cap 6 Chapter 6 Loops 58 Cap 7 Chapter 7 Errors 80 Cap 8 Chapter 8 Subprograms and Modules 86 Cap 9 Chapter 9 Arrays 108 Cap 10 Chapter 10 Advanced Input and Output 126 Cap 11 Chapter 11 Handling Characters 141 Cap 12 Chapter 12 Derived Types Structures 152 Cap 13 Chapter 13 Pointer Variables 171 Cap 14 Chapter 14 Simulation 186 Cap 15 Chapter 15 Matrices and Their Applications 197 Cap 16 Chapter 16 Introduction to Numerical Methods 224 App B Appendix B Summary of Fortran 90 Statements 248 App C Appendix C Intrinsic Procedures 265 App D Appendix D ASCII Character Codes 273 App E Appendix E Solutions to Selected Exercises 274 Introduction to Fortran 90 for Scientists and Engineers An easy to use online version of Fortran 90 for Scientists and Engineers by Brian Hahn is provided with Fortran PowerStation 4 0 for your use If you find this book helpful and would like a paper copy an order form has been provided You can either print the order form and mail it to the address provided phone in your order or use email to order the book Fortran 90 for Scientists and Engineers Brian D Hahn Department of Applied Mathematics University of Cape T
191. It generates a uniformy disribted pseudo random number in the rang M W L a al x L 2a L 0 lt x lt a 2 PE 2 3 lt x lt M Wa al 2L x 3L 2a L a lt x lt L A computer canno generete truly random numbers but they can be practically unpredictable R may be a scalar or an array but it must be GC real E g REAL DIMENSION 10 R CALL RANDOM NUMBER R PRINT E14 7 R Output 1077691E 01 1275343E00 4685287E00 5612317E00 6204859E00 5067996E00 7804365E00 7967151E00 3911508E00 7211771E 01 m o A a E o E e E a E E E e Or Of course if you re usethis piece of code again you will get exactlythe same sequence of random numbers which is rether disappointing and not true to life as every gambler knows To produce a different sequence each time the generator can be seeded in a number of ways Here s one way INTEGER Count REAL DIMENSION 10 R INTEGER DIMENSION 1 Seed CALL SYSTEM C OCK Count Seed Count CALL RANDOM SEED PUT Seed CALL RANDOM NUMBER R PRINT E14 7 R The intrinsic subroutine SYSTEM CLOCK returns in its first integer argument the current value of the system clock A second optional argument returns the number of clock counts per second RANDOM SEED has an optional dummy argu
192. LE NAMES EOF 0 IT l DO WHILE EOF 0 read list of names READ 1 A20 IOSTAT EOF Item IF EOF 0 THEN Names I TRIM Item I I 1 END IF END DO N I 1 Index 100 all positions initially unoccupied DO I 1 N construct hash list CALL Place I Index Names END DO Item now look for Items DO WHILE Item PRINT Search for READ Item I H tem TRIM Item Find Index Names Item 168 IF H gt 0 THEN PRINT Names H found in element H of Names ELSE PRINT H not found END IF END DO CONTAINS FUNCTION Find Index Names Item Hashes Item to integer K which is increased by InK if or a match Item Names Index K is found If no match is found Index K is returned INTEGER F Find H I Ink K INTEGER DIMENSION Index CHARACTER DIMENSION Names CHARACTER Item H 0 DO I 1 LEN TRIM Item hash it H H IACHAR Item I I IACHAR Item I I END DO K MOD H Mn 1 InK MOD H Mn2 now we look until we find an unused position or a match F 1 DO WHILE 1 IF Index K 100 THEN F K ELSE IF Item Names Index K THEN F Index K END IF K MOD K InK Mn 1 END DO Find F El ND FUNCTION Find UBROUTINE Place J Index Names items Names The item in Na
193. ND DO PRINT Mean SUM N This isthe crudest solution to the problem the data must be supplied one value per lire inthe file More elegant solutions will be given later IOSTAT is a specifier whichis se to zero ifthe READ succeeds or to a negative value if an end of file condition occurs during the READ It is discussed more fully later Taylor series for sine You may have wondered how a computer calculates functions such as sine and cosine Really anciert computers actually used to look up tables entered in memory but young and upwardly mobile ones are more cunning Mathematically it can be shown that sin x for example isthe sum of an infinite series called a Taylor series as follows 3 5 7 X X X 3 5 7 sinx x We obviously can t computethe sum of an infinite series but we can at least arrangeto stop afterthe terms in the series are all less than some prescribed value say 10 Tt can be shown that we can always get aterm lessthan some arbitrarily small number by going far enough inthe Taylor series As an exercise you should try to draw a flowchart or structure plan before studying the program below The mainidea isto construct each term inthe series from the previous one as described in the limit problem in Section 6 1 In constructing the denominator each time use has been made of the fact that if k is any integer 2k is even and 2k 1 is odd So
194. ND FUNCTION Fung INTERFACE o Fl El N Simp 0 N NINT B A 2 H 2N panels now DO I 1 N 1 using notation defined in text Simp Simp 2 Fung A 2 I H END DO DO I 1 N Simp Simp 4 Fung A 2 I 1 H END DO Simp H 3 Fung A Fung B Simp END FUNCTION Simp Note that N ishalf its previous si _ 3 If you try Simpson s Rule out on J x TN between any limits you will find rather surprisingly that it gives the same result asthe exact mathematical solution This is a nice extra benefit of the rule it irtegrates cubic polynomials exactly which can be proved 16 3 Numerical Differentiation The Newton quotient for a function J x is given by f x h f x h 16 4 df dx where his small As 4 tends to zero this quotient approaches the first derivative 231 The Newton quotiert may therefore be used to estimate a deriv ive numerically tis a useful exercise to do this with a few functions for which you know the derivatives This way you can see how small you can make h before rounding errorsrounding error cause problems These arise because Expression 16 4 involves subtractingt wo terms that eventually become equal whenthe limit of the computer s accuracy is reached RS As an example the follow
195. NQUIRE by unit ad INQUIRE by file Inquiry by output list has the form INQUIRE IOLENGTH length output list This form may be used to establish the length of the unformatted record of an outjout list An example of inquiry by unit number is T INQUIRE UNIT Ju EXIST allowed The logical variable allowed willbe assigned the value TRU number for your system and FALSE ctherwise Gl if unit number u is an allowed unit The existence of a file may be established similarly INQUIRE FILE filename EXIST allowed You can use the EXIST specifierto avoid accidentally overwriting or deleting an existing file The number of the record most recently read or written is tumed withthe NEXTREC specifier Further details are in Appendix B 10 8 Non advancing I O Normally READ and WRITE transfer complete records This can be a nuisance A new feature of Fortran 90 is non advancing 1 0 whereby a file is left positioned within the cumrert record We have seen the use of non advancing WRITE in giving screen prompts WRITE A ADVANC READ Number Gl NO Enter a number Non advancing READ can also be useful for example in reading individual characters from a text file The following program counts the number of characters in a
196. O PRINT Total cost TotCost END There are a number of important poirts to note e 6InFortran 90 terms the arrays C and X havet wo dimensions rank two Each dimension has an extent of 3 andthe shape of the arrays is 3 3 e You might be wondering why the DATA statements need implied DO loops Wouldn titbe much simpler to say DATA C 37 127 10 Ty 185 35 7 T0 247 198 This raises an extremely importart poirt which has caused many a programmer to come to grief Certain Fortran statemerts such as DATA READ and PRINT treatthe elements of multi dimensional arrays in a particular order when the array is referenced by its name only This order is called the array element order and is obtained by changing the eft most subscript most rapidly This is the reverse of odometer order where the right most subscrit changes most rapidly and which is used inmany her languages As a result the briefer fom of the DATA statement used in this note is equivalent to th following assignments C 1 1 3 C 2 1 12 C 3 1 10 C 1 2 17 C 2 2 18 C 3 2 35 C 1 3 7 C 2 3 10 C 3 3 24 Although it makes no difference to the answer hers the table is not represerted by the conventional row column order depicted in Figure 15 1 Itis therefore always necessary to use implied DO loops when initializing or reading multi dimensional arrays ifthe
197. ON 0 10 F 1 0 12 9 31 26 49 26 amp 24 6 1 10 FORMAT T3 13 13 60A1 20 FORMAT 100 6X I3 60A1 DO I 0 10 IF I lt 10 THEN PRINT 10 10 I 10 I 9 F I J 1 F T ELSE PRINT 20 F I J 1 F I END IF END DO END Output 0 9 1 10 19 O 20 e 29 12 RRR RKRKKKKKK 30 pi 39 Q RRR KKKKKK 40 wai 49 BL eR RRR KRAERKKRKKERKKKEKKEKKKKERKKKKK KK 50 pa 59 26 pRRREAKREKKKKKKRKKKKEKKKKKE 60 69 49 gE RKRKKEKKKRKKER KEE KKKEKKKK KER KK EKKEKEKKKEKKK KKK ERK KKK EK 70 a 79 26 xxx kkkkkkkkkkkkkkkkkkkkkkK 80 89 24 ikk kkkkkkkkkkkkkkkkk kkk k 90 99 6 100 1 142 Note the absence of asterisks forthe 10 19 decile This is because F 1 hasthe value zero so that the implied DO inthe PRINT statement has a zero trip count when I has the value 1 Of course in a real situation the frequencies will n be presertedto you neatly on a plate You are more likelyto have a list of the actual marks You should adapt the program to read a sample set of marks inthe range 0 100 and to convert them irto fi encies The basic mechanism is READ MARK K INT MARK 10 K is the decile F K F K 1 another mark in the Kth decile 11 3 Sorting Words Characters may be comparedin IF statements thisisthe basis of alphabetic sorting Each computer system has a collating sequence which specif
198. Pi phase degrees PRINT 10 Omega A B ABS T Phase 10 FORMAT F7 3 T10 E11 4 T25 E11 4 T40 E11 4 T60 F7 2 Omega Omega Fact END DO Sample output Omega Real T Im T Abs T Phase 0 020 0 3024E 04 0 4483E 05 0 4493E 05 93 86 0 025 0 3018E 04 0 3578E 05 0 3591E 05 94 82 120 371 0 1651E 01 0 1830E 01 0 2465E 01 132 07 150 463 0 7512E 02 0 1100E 01 0 1332E 01 124 33 Tf you run the program you will see how the input signalis amplified at first but isthen attenuated The phase shift starts at abou t 90 and moves gradually to about 180 after which it swings backwards and forwards across the real axis as the input fi ency gets larger 6 2 The DO in General Try the following program segments output is shown aftereach one DO Ea By 2 WRITE 13 END DO ea ll Gl ADVANC NO I Output 2 4 6 DO I 5 4 WRITE END DO 5a I3 ADVANCE NO I Output ncthing DO I 5 1 l WRITE 13 END DO ea ll ADVANC NO I Output 54321 DO I 6 WRITE END DO dep eZ 13 ea ll ADVANC NO I 61 Output 6 4 2 The general form of the DO construct that we shall use is name DO variable expr expr2 L expr3 block END DO name where variable the DO variable is an irteger variable exprl expr2 and expr3 are any valid irteger expression
199. Preface which indicates wherethe new features may be found You will also need to know that some old features have been declared obsolescent These which may include some of your old favourites have been made redundant by the new standard and are recommended for deletion in the next standard i e the recommendation is not binding Appendix B contains a summary of all Fortran 90 statements and indicates which are obsolete and or not recom mended 1 3 Running Fortran Programs If you are new to Fortran you should run the sample programs in this section as soon as possible without trying to understand in detail how they work Explanations will follow in due course You will need to find out from a manual or from someone else how to enter and run Fortran programs on your computer system Greetings This program will greet you if you give it your name My first Fortran 90 program Greetings CHARACTER NAME 20 PRINT What is your name READ NAME PRINT Hi there NAME END You should get the following output your response is in italics What is your name Garfield Hi there Garfield AIDS cases The following program computes the number of accumulated AIDS cases A t inthe United States in year t according to the fomula A t 174 6 t 1981 2 PROGRAM AIDS Calculates number of accumulated AIDS cases in USA INTEGER T year RE
200. R1 R2 However ifthe ordinary as opposed to pointer assignment statement Pl P2 is cuted next the situation is as follows R1 R2 Note that this assignment has exactly the same ffect as Rl R2 since P1 is an alias of R1 and P2 isan alias of R2 To sum up e Poirter assignments such asP gt Q s amp up the poirter P as an alias of Itstarget Q e A referenceto a poirter variable e g in an assignment or expression isin fact a reference to its tan variable Poirter assignment changes a currert alias The statement P2 gt Pl following the code above changes the target of P2 tothat of P1 sothat P1 and P2 are now both aliases of R1 R1 R2 P1 a Pointer states Any poirter in a program is always in one of the following three states e t may be undefined al1 pointers are in this tate at the beginning of a program e TE may be null see the NULLIFY statement below this means that itis not the alias of any objed e i may be associated seethe ASSOCIATED intrinsic function below this means that itis the alias of some objet The NULLIFY statement 173 As just mentioned a poirter is undefined at the beginning of a program However it is sometimes convenient fora poirterto be poirtingto nothing or not poirtingto anything This isthe null state and is achieved by the statement NULLIFY P1 where P1 is a poin
201. RCE copies of PAD are inserted irto the result after SOURCE ORDER must be an integer array withthe same shape as SHAPE Its value must be a permutation of 1 2 n TEappears to control the way inwhich SOURCE and PAD are combined T SPREAD SOURCE DIM NCOPIES makes NCOPIES duplicates of SOURCE by increasing itsrank by 1 DIMisthe dimension ofthe result along which duplicationtakes place See Chapter 15 for a program which generates examples TRANSPOSE MATRIX trenspose of rank two array MATRIX UNPACK VECTOR MASK FIELD array of type of VECTOR and shape of MASK VECTOR must be rank one array of size at least the number of true elements of MASK The element of the result corresponding to the ith true element of MASK is the ith element of VECTOR all cthers are equal to corresponding elements of FIELD ifitis an array withthe same shape as MASK orto FIELD if tisa scalar C 10 Inquiry Functions for Any Type ASSOCIATED POINTER TARGET If TARGET is absent result is TRUE if POINTER is associated with a target FALSE otherwise The status of POINTER must n be undefined If TARGET is present result is TRUE if POINTER is associated with it If TARGET itselfis a pointer its targ amp is compared with the target of POINTER and FALSE is rtumed if either POINTER or TARGET is disassociated
202. REAL POINTER X 258 ALLOCATE X N PRINT sends output to the dandard output unit Output may be formatted or lis directed PRINT The answer is X Y list directed PRINT A F5 2 The anser is X PRINT 10 The anser is X labelled format 10 FORMAT A F5 2 PRINT A I J J 1 N I 1 N implied DO P P T F am p componerts of derived types See REAL and TYP RIVAT Eal specifies the PRIVATI atribute for some or all of the entities in a module and for GI ROGRAM optionally names a program PROGRAM MyOne ND PROGRAM MyOne name can t appear without PROGRAM UBLIC specifies the PUBLIC attribute for module entities See REAL Statements R through S 1 RI RI EAD transfers ta from an input vi thas a number of forms e g EAD A B C list directed from standard input evice EAD A B C list directed from standard input evice EAD 5 A B C list directed from unit 5 BAD 1 15 A B C from unit 1 format labelled 15 5 FORMAT 3F6 2 FAD 3F6 2 A B C from standard input device BAD 1 A B C from unit 1 unformatted The general form is RI EAD UNIT u FMT fmt spec list list 259 The specifiers may be in any order subject tothe following conditions ifthe UNIT keyw
203. SION 10 A B 5 C 4 4 only A is rank 1 size 10 REAL OPTIONAL INTENT IN Y optional dummy argument REAL INTENT INOUT M dummy only Certain fairly obvious combinations of attributes are not allowed e g POINTER on the one hand and TARGET orINTENT on the ALLOCATABLE E A kind parameter may be speci RECURSIVE speci fies a recursive procedure RETURN reuns control f otha TARGET and PARAMET ER POINTER and fied for any type See FUNCTION a subprogram at a point ctherthan its END statement This can leadto unstructured design and should be avoidedif possible There is ancther form of RETURN calledthe altemate RETURN which is obsolescent and not recommended because it allows returns to altemate poirts inthe calling program CALL GUNGE A B C 10 30 CONTAINS SUBROUTINE GUNGE X Y Z RETURN 1 RETURN 2 END SUBROUTINE GUNGE m z UO 261 Tf the integer expression in the RETURN asterisks in the dumm isthe actual argument statement is lessthan 1 or gre er than the number of y argument lig a normal return is executed Le to the poirt of call Otherwise if ithas the value i control passestothe statement inthe calling program whose label corresponding tothe ithdummy asterisk So RETURN 1 effectsa retumto
204. T Current I END 275 Chapter 3 276 10 11 lt T3 INTEGER C DO C 20 30 F 9 C 5 32 NT C F INTEGER I DO I 10 20 PRINT Ey SORT 1 1 SQRT may not have an integer argument END DO INTEGER I SUM 0 nN C ES DO I 1 100 SUM SUM 2 I I DO ea Z J TEGER I N NumPass AL Avg Mark mPass 0 0 10 EN 1 FI OoI 1 N EAD 1 Mark Avg Avg Mark IF Mark gt 5 NumPass NumPass 1 END DO Avg Avg N PRINT Average Avg PRINT NumPass passed L Gl Marks JAT eee Fl Il Q A 4 X 1 1 2 1 3 1 4 DO K 1 4 X X 1 K END DO The limit is pi REAL Bal Dep Intr Rate INTEGER Mon Bal 0 Dep 50 Rate 0 01 Ww PRINT Month DO Mon 1 12 Bal Bal Dep Intr Rate Bal Bal Bal Intr PRINT Mon ND DO ND Balance Ww Bal m m 16 A B K EGER T 197273000 0 03134 191325 PRINT A5 DO T 1790 2000 10 P K 1 EXP A PRINT 1I5 F20 0 T D DO D P EA NT A20 Year T B P ee N N 18 INT A EGER Feet R Inches READ Metres Inches 39 37 Metres Yards Inches 36 Inches MOD Inches Feet Inches 12 Inches MOD Inches PRINT Imperial Yards Metres 1S
205. Temp and X actually involve poirter assignments of their Key componerts again because of the alias set up If you are confused by this and who wouldn t be convince yourselfthat a list of two records will be correctly aered by drawing some diagrams of the aliases Note that this approach uses more memory than a key file since the studert records must be inthe array Student to mairtain the aliases 13 2 Linked Lists One of the classical and most powerful applications of poirters is in setting up and manipulating linked lists Tt is also one of the most diffiailt to understand I usually have to resort to drawing a ict of diagrams before I can follow what is going on A thorough study of linked lists and related topics such as binary trees is beyond the scope of this book and not in keeping with its ethos so only relatively simple examples will be given here 178 The basic idea is to represent a list of values with a chain of dynamic variables all linked together as an alternative say to an aray Each of these variables should holda value and also point to the next variable inthe chain Such a variable is called a node t could havet wo componerts a value and a pointerto another node Fortran 90 allows the following rether curious type definition TYPE NODE INTEGER Value TYPE NODE END TYPE NODE Fl
206. UF H Z Hn REAL A B x eal D D A B CALL SWOP A B More general access to irterface blocks may be provided by means of modules Itefa blocks are also used for overloading a number of subprogram names with a single generic name When to use interface blocks It is never wrong to use an interface block for an external procedure However there are situations when one must be used These are summarized in Figure 8 1 We will encounter most of these situations later they are collected here for ease of reference Figure 8 1 When to use an interface block 94 An interface block is needed to call an external procedure in the following cases when the procedure is called with a keyword and or missing argument when a procedure is called which defines or overloads an operator or the assignment when the procedure called is an array valued function or a character function which is neither a constant nor assumed length when the procedure callled has a dummy argument which is an assumed shape array a pointer or a target when the procedure is a dummy or actual argument when the procedure is called using a generic name 8 5 Modules Recall that there are three types of program unit a main program an external subprogram anda module A module differs from a subprogram in two importart ways e a module may contain more than one subprogram called module s
207. UNIT u IOSTAT io ERR label amp STATUS st See OPEN forthe meanings of the first three specifiers st is a character expression which must have the value KEEP or DELETE This specifies what happens tothe file after disconnection st defaultsto KEEP unlessthe file has status SCRATCH in which case its only value is DELETE COMMON not recommended allocates memory ina COMMON block of starage which may be blank or named The blocks may be accessed from differert program units using the same or different variable names E g COMMON JUNK A B X 5 in one program unit and COMMON JUNK X Y 4 Z1 Z2 inanother meansthat A and X Band Y 1 X 5 and Z2 sharethe same storage locations As you can imagine this can be highly dangerous If data must be shared bet ween program units it should be declared in a module accessed by any program units needing it Blank COMMON refers tothe unnamed COMMON block of which there is only one COMMON M G COMPLEX specifies complex type COMPLEX X X 0 1 sqrt 1 Complex constants in Hist directed input with READ must be in parentheses CONTAINS signals the presence of one amore irternal or module subprograms CONTINUE is a dummy statement which does nothing Itsmain usage was as a labelled stateme
208. WRITE I4 projection F6 0 Year 1 Tot PRINT END DO END Chapter 6 Summary e A DO construct with parameters should be used to program a deterministic loop where the number of iterations the iteration count is known to programmer before the loop is encountered This sit the program Le in principle to the ion is characterized by the general structure plan Repeat Ntimes Block of statements to be repeated e where N is known or computed before the loop is encountered for the changed by the block The syntax for DO in this case is name DO variable first last step block END DO name All forms of the construct may be optionally named first time and is not Tf step is omitted it defaultsto 1 If step is negative variable willbe decreased as long as first is greater than or equal to last e DO with EXIT may be used to program a non deterministic loop where the iter ion count is not known in advance i e whenever the truth value of the condition for exi ing is changed in the DO block This situation is characterized by the following two structure plans Repeat until wndition is m Block to be repeated reset tuth value of condition or Repeat Block to be repeated reset tuth value of condition until condition istrue Note thet condition isthe condition to
209. a Zz P 1 RINT EAD N DO K 1 1 N 1 Rate Year ER K N NPos 1 NZer NPos V 0 T coincide AND V parallel Ds iC Y r X Y 1 0 15 i 180 2F7 4 X e Year 10 Ty L2 Bal Bal Sign and v 0 0 and v 0 are y V X Y HEN 0 THEN convert to radians SIN Ang COS Ang Number of terms then coincide then af dc u 279 280 W El END DO Sign Sign Pi Pi Sign 2 K 1 0 avoids integer division REAL Pi 0 INTEGER K N PRI REA NT Number of terms D N DO K 1 N Pi Pi 1 0 4 K 3 4 K 1 avoids integer division END DO Pi 8 Pa REAL 2 E X greatest precision X 0 1 E 1 0 1 X 1 xX PRINT X E Xf EO END DO 1 PARAMETER Pi 3 1415927 NT ANT D N 0 DO WHILE T lt Fourier 0 N REA REA INTEGER K N PRI REA T 1 SPACING T make sure we hit 1 0 DO K 0 Fourier Fourier SIN 2 K 1 Pi T 2 K 1 END DO Fourier 4 Fourier Pi PRINT T Fourier T T 0 1 ND DO m INTEGER Ans I Sum 0 I 0 NumTerms Sum DO IF Sum gt 100 EXIT Ans Sum since Sum will go over 100 NumTerms I I I 1 Sum Sum I ND DO RINT Ans afte
210. a character argument You may be wondering how the same function can take arguments of so many differert types If so you will have to wait forthe discussion of overloading to see how this may be done 3 6 Complex Type Complex numbers and complex arithmetic are supported by Fortran 90 E g COMPLEX PARAMETER i 0 1 sqrt 1 COMPLEX X Y X 1 1 Y 1 1 PRINT CONJG X i X Y Output 1 0000000 1 0000000 0 0000000E 00 2 0000000 When a complex constant is input with READ it must be enclosed in parentheses Many of the intrinsic functions can take complex arguments 3 7 Introduction to Intrinsic Functions So far you should be able to write a program which gets data into the computer performs simple arithmetic operations on the data and outputs the results of the computation in a comprehensible form However more interesting problems are likely to involve special mathematical functions like sines cosines logarithms etc Just as most calculators have keys for these functions Fortran allows you to compute many functions directly These functions are called intrinsic or built in functions Projectile motion We want to write a program to compute the position and y co ordinates and the velocity magnitude and direction of a projectile given f the time since launch u the launch velocity a the initial angle of launch in degrees and g the acc
211. adrant is given which is n the case for ATAN The program below shows how the servomechanism responds to different input frequencies This information is necessary inthe design of stable feedback contral devices The initial input frequency is 0 02 radians sec This is multiplied by a factor Fact of 1 25 each time for a given number of steps The amplification factor K is 900 The phase shift b of the output isgiven in degrees Notethat a named complex constant i is used for V 1 The complex variable iom is formed from i and Omega purely for nctational convenience IMPLICIT NONE INTEGER N counter INTEGER Steps iteration count REAL A B Re T Im T REAL 23 Fact 1 25 scaling factor REAL Sick 900 amplification REAL Omega 0 02 angular frequency REAL Phase phase angle REAL PARAMETER 3 RL 3 1415927 COMPLEX PARAMETER i 0 1 l sqrt 1 COMPLE iom sqrt 1 omega oN COMPLEX T complex transfer function READ Steps PRINT 20 20 FORMAT Omega T12 Real T T27 Im T T42 Abs T amp T62 Phase PRINT DO N 0 Steps iom i Omega T K 1 0 4 iom 1 0 2 iom amp iom 1 2 5 iom 1 1 43 iom 1 0 02 iom 2 A REAL T B AIMAG T Phase ATAN2 B A 180
212. al or integer soKIND 0 will return the default irteger kind The simple ceclaration INTEGER I specifies I with default integer kind default The function HUGE I returnsthe largest value represented by its argument real orirnteger To find the smallest value simply add 1 and print the result The values of an integer kind cycle bet ween their lower and upper bounds under the FTN90 compiler The following fragment will estallish default irteger kind and upper and lower bounds INTEGER BIG HUGE I SMALL BIG 1 PRINT Default kind KIND I PRINT Largest PRINT Smallest SMALL Note that the argumertts of KIND and HUGE need n be defined Having established the default kind parameter value you can experiment a bit to establish the other kinds available on your compiler E g the statement INTEGER KIND 2 I specifies I with a kind parameter of 2 m ore precisely a kind type parameter contents of square brackets is optional The function SELECTED INT KIND N returnsthe kind parameter value forthe kindthat will N N be able to represert all integer values in the rang 10 to 10 This function can be used to estalblish what kinds are available INTEGER K N 0 N 1 SELECTED INT _KIND N K 1 EXIT f 32
213. already nearly sorted try it on a sorted lis However it will work just as fast inthis case if you choose a value near the middle of the subproblem for the partition value instead of the left most value Happy sorting 9 8 More Array Features Fortran 90 has some powerful new array features which are ideally suited to numerical analysis applications They are summarized in this section Array constructors A one dimensional consart array may be constructed from a lit of element values enclosed between the separators and E g 2 4 6 8 10 is an array of rank one with five elements The general form of an array constructor is array constructor value list where each value is either an expression oran implied DO of the farm value list variable expr1 expr2 expr3 m The parameters of the implied DO operate in the same way as those of the DO 2 4 6 8 10 The optional parameter expr3 is sometimes called the stride in the context of an implied DO An implied DO may be nested inside ancther making 119 Tf the lit is empty a zero sized array is constructed The scope of the implied DO variable is restricted to the implied DO it will n affect the value of andher variable of the same nam elsewhere in the scoping unit of the constructor A consta
214. am END statement but doligatory inthe irternal subprogram END statement Note also that since an extemal subprogram resides in a separate file from the main program it must be compiled separately Under FTN90 an intemmediate type of machine code called relocatable binary is produced in a file with the OBJ extension Thisintum must be linked withthe calling program by means of a special program called a linker finally resultingin a EXE version of the main program Your compiler manual will have the details of how to dothis Once itis finally debugged an external subprogram need never be recompiled only linked This prevents you from wasting time in compiling it over and over which would be the case if it was an internal subprogram As an example let s rewrite the internal subroutine SWOP of Section 8 1 as an external subroutine The main program in one file becomes IMPLICIT NONE EXTERNAL SWOP REAL A B READ A B CALL SWOP A B PRINT A B END and the external subroutine in a separate file isthen SUBROUTINE SWOP X Y REAL Temp X Y Temp X X Y Y Temp END SUBROUTINI Gl The EXTERNAL statement is discussed below You should now try compiling linking and running this example If you want morethan one external subprogram
215. an a letter or a blank willendthe loop VERIFY ensuresthat only a genuine name is written tothe file Rememberthat READ assumes that a string without delimiters is terminated by a blank so if you want to read blanks as part ofthe string you must either use a formatted READ or enclose the string in delimiters Both components of Student are written to record number RecNo by the single WRIT statement after which RecNo must be incremented zal If you ever have to write a program of this nature which other people will use you will soon discover that most of your programming effort will go irto anticipating and trapping their stupid mistakes In particulary a crash must be avoided if the user makes an invalid response The short subroutine ReadIntCon makes use of the IOSTAT specifier to irtercect a READ error SUBROUTINE ReadIntCon Num INTEGER Err Num Err 1 remember to initialize DO WHILE Err gt 0 READ IOSTAT Err Num IF Err gt 0 PRINT Error in mark re enter END DO SUBROUTINE ReadIntCon ea Z o ii 161 DisplayRecords usesa DO WHILI file is detected by the IOSTAT specifier E construct to read and display the SUBROUTINE DisplayRecords RecNo 1 EOF 0 DO WHILE EOF 0 READ 1 REC Re
216. ariety of mathematical trigonometric and cther functions directly Exercises 3 1 Translate the fallowing irto Fortran statements Add 1 tothe value of I and tore the result in I bd Cube I add Jtothis and tore the result in I Cc Set G equal tothe larger of the two variables E and F q Tf Dis greater than zero set X equal to minus B Divice the sum of A andB by the product of C and D and store the result in X 3 2 If C and F are Celsius and Fahrenheit temperatures respectively the formula for conversion from Celsius to Fahrenheit is F 9C 5 32 Write a program which will ask you forthe Celsius temperature and display the equivalent Fahrenheit one with some sort of comment e g The Fahrenheit temperature is Try it out on the following Celsius temperatures answers in parentheses 0 32 100 212 40 40 37 normal human temperature 98 6 10 Change t Celsius temperatures ranging fi t displays a list of integers 3 3 Write a program that root next to ik 3 4 Write a program to 5050 m 20 to 30 in teps a he program to use a DO loop to compute and write the Fahrenheit equivalent of Eie ran 10 to 20 inclusive each with its square find and display the sum oft he successive integers 1 2 100 Answer 3 5 Write a program to find and display the sum of the success
217. assignment A structure may appearinan VO lis as long as there is an appropriate format specification for each component Structures of the same type may be assigned to each cther All corresponding components are assigned The assignment operetor may be redefined for derived types by overloading it using an INTERFACE ASSIGNMENT block New operators may be defined for derived types from a sequence of characters enclosed in decimal poirts suchas IN or intrinsic operators may be overloaded using an INTERFACE OPERATOR block A function may be structure valued A derived type appearing in a module may be declared PRIVATE The type and all its components are then only accessible inthe module Ifthe PRIVATE statement appears in the definition the type name is accessible outsice the module although the components are not An entity n part of a bigger entity is called an object An array is any object that is mt a scalar single valued A variable now means any named object not a constant and any part of such an object Chapter 12 Exercises 12 1 Extend the Student_Records program in Section 12 2 to compute and display the average mark as part of the subroutine DisplayRecords 12 2 As a project extend the Student_Records program in Section 12 2 to accept further marks offerings for each student
218. ates spinning a coin 50 times and repeatsthe simulation five The initial seed is once again generated by the system clock and RANDOM_S each simulation At the end of each simulation another optional argument GET is usedto set Seed HHTTTHTTHHAATTHHATTTTTTATTATHTTHTITTHATHTTHAHHTTTHAT HTHTTTHTTHATHTTTTHTHHTHHATTTTATTTITTITTTTATTATTTTHAT TTTHTTHHHTTHTTTHHATTHHATTTTHTHHHTTHTATTHHTTHHHHATT HTHTHHTHHHHHTTHTHTTTHHHHHTTHHTTTHTTTTHHHHTHHTTTTHH HTHHTHHHTHTHHTHHTHTTHHHTHTTHTTTTHHHTHHTHTTTTTTTHTH T ED is used to seed tothe currert value of the seed eachtime a random numberis generatedthe seed is reset internally This means that an unbroken sequence of random seeds is used for the entire set of simulations theoretically this is preferable to reseeding the process with the system clock for each simulation Note the use of the WHER random numbers R Note also that it should be impossible in principl experiment was simulated or real ifthe random number generetor is sufficiertly random 14 3 Rolling Dice to tell E construct to generete the array of results COINS from the array of rom the output alone whether the When a fair die plural dice is rolled the number uppermost is equally likely to be any integer from 1 to 6 The following program segment simulates 20 rolls of a die The output from two successive runs is shown
219. ations are goingto be needed until afterthe program has run although in this example perhaps you could work out in advance how many iterations are needed If you want to writethe new balance only while it is less than 2000 all that has to be done is to move PRINT Year Interest New until it isthe first statement inthe DO loop try it Note that the starting balance of zero is written now The EXIT condition can be placed at the top of the original DO block if it is rephrased as follows IF New lt 2 Old EXIT Note that gt has been replaced by lt Try this also Either form is acceptable although the purists might prefer the version with EXIT at thetop This condition is immediately apparent to anyone reading the program you do not have to search forthe end of the loop to find the condition to exit Prime numbers Many people are obsessed with prime numbers and most books on programming have to include a program totest if a given number is prime So here s mine A number is prime ifitis ng an exact multiple of any other number excerpt itself and 1 Le if it has no factors except itself and 1 The easiest plan of attack then is as follows Suppose P isthe number to be tested See if any numbers N can be found that divide into P without remainder If there are none Pis prime Which numbers N should we try Well
220. auss inthe program below performs a Gauss reduction on a system of any size The augmented array A is passed as an argument On entry its rightmost column should contain the right hand sice constants of the equations On return the rightmost calumn will contain the salution PROGRAM GaussTest IMPLICIT NONE REAL DIMENSION ALLOCATABL INTEGER I J N Gl A augmented matrix PRINT How many equations 218 EAD N LOCATE A N N 1 extra column for RHS RINT Enter augmented matrix by rows EAD A I J J 1 N 1 I 1 N CALL Gauss A PRINT D D PRINT Solution is in last column O TS ty N PRINT 10F7 2 A I J J 1 NELJ END DO CONTAINS SUBROUTINE Gauss A EAL DIMENSION A EAL PivElt TarElt NTEGER N number of equations NTEGER PivRow TarRow Ll HH D N SIZE A 1 DO PivRow 1 N process every row PivElt A PivRow PivRow choose pivot element A PivRow 1 N 1 A PivRow 1 N 1 PivElt divide whole row now replace all other rows by target row minus pivot row times element in target row and pivot column DO TarRow 1 N IF TarRow PivRow THEN TarElt A TarRow PivRow A TarRow 1 N 1 A TarRow 1 N 1 amp A PivRow 1 N 1 TarElt END IF END DO END DO ND SUBROUTINE Gauss N
221. ave been changed being copied back again on return It is bad programming style for dummy arguments of function subprograms to be changed in this way if you need more than one value back from a function rewrite it as a subroutine Value arguments Tf an actual argument is a constant or an expression more complex than a variable it is passed by value This meansthatthe value of the actual argument is literally copiedtothe dummy argument Changes made tothe dummy argument are consequently not reflected inthe actual argument on return TE should be noted that enclosing a variable in parertheses makes it an expression So the first argument of CALL Plonk X Y is passed by value Ifthisis not what was intended it can be very difficultto spct This very subtle error can be prevented by giving dummy arguments an intent this is discussed next Argument intent Dummy arguments may be specified with an intenf1 attribute i e whether you irtendthem to be used as input or output ar both eg SUBROUTINE PLUNK X Y Z REAL INTENT IN sop REAL INTENT OUT eee ei REAL INTENT INOUT Z Tf irtert is IN the dummy argument may n have its value changed insice the subprogram Tf the intert is OUT the corresponding actual argument must be a variable Such a specification would prevent the last error mentioned above since a call such as
222. ay I be safely incremented EN TRIM returns the length of Str As blanks are removed this value will of course be reduced To keep matters simple the searching procedure isthe crudest one possible read each record inthe file from the beginning urtil either a match is found or the end of fileis reached Ifa match is found update the mark and rewrite that record If no match is found report so More sophisticated searching procedures are discussed below you can buildthem irto this program if you like Once UpDate has found a match the user enters the corrected mark and the record is rewritten You can easily add other featurestothis basic skeleton e g prirking names and marks analysingthe marks deleting a name amp c You could also extend the database to include an array of marks Practically the only disadvantage of using a direct access file as opposed to a text file is that the record length is fixed So if you wanted to allow for an array of say 20 marks the record length must be increased eventhough you may never use the extra space One way out isto create a new direct access file each time a new set of marks is entered with room for only one additional mark and to rename it withthe original name 12 3 A Binary Search We have seen already how to sort numbers and words Items are usually sorted only s
223. ay elements according to a logical mask Exercises Tf Num is an integer array with the attribute DIMENSION 100 writethe lines of coding which will put the first 100 positive integers 1 2 100 irto the elements Num 1 Num 100 put the first 50 positive even integers 2 100 irtothe elements Num 1 Num 50 Assign the irtegers in reverse order Le assign 100 to Num 1 99to Num 2 amp c endalphalis Write some statementsto put the first 100 Fibonacci numbers 1 1 2 3 5 break 8 into an array F 1 F 100 Salary levels at an educational institition are inthousands of dollars 9 10 12 15 20 35 and 50 The number of employees at each level are respectively 3000 2500 1500 1000 400 100 25 Write a program which finds and writes the average salary level The number of employees above and below the average level The average salary earned by an individual in the instituticn 123 Write a program which reads 10 numbers into an array and prirtsthe mean andthe number inthe array furthest in absolute value from the mean Develop a structure plan forthe problem of writing all the primes less than 1000 1 and 2 are generally regarded as primes prime number generetionand will probably have to be dealt with separately Writethe program Hint use an arra
224. bal contains declarations to be used by DI Eqs andDrUtils MODULE DrGlobal Global declarations for Driver TYPE VarType type for model variables Character 4 Name name REAL InVal initial value REAL Val current value END TYPE VarType TYPE ParType type for model parameters Character 4 Name name REAL Val value END TYPE ParType TYPE ParType ALLOCATABLE TARGET Params parameters TYPE VarType ALLOCATABLE Vars variables REAL ALLOCATABLE TARGET X current values of variables REAL T dt model time and step length for Runge Kutta INTEGER Itime RunTime counter number of integrations INTEGER NumVars NumParams number of model variables parameters Character 1 Opt response to main menu END MODULE DrGlobal Each element o variable name initial value and currert value The current value is kept so thatthe user may run the f the array Vars of derived type VarType represents properties of a model model either parameters m the initial values or the current values The array Params representsthe model Eis convenient to have a separate array X to holdthe currert values of the model variables t has the TARGET attribute to allow aliasing in DEqs The her va
225. broutines in firtis SetWindow Xmin Xmax Ymin Ymax which sets upthe world co ordinates of your problem i e the rectangular region of your co ordinate 199 system which will be plctted So if you want a vertical range between 1 and 1 call SetWindow with the following arguments CALL SetWindow 0 0 4 Pi 1 0 1 0 Note that the arguments must he real irteger constants will cause an error You then need to set up two one dimensional arrays X and Y say in general where X I and Y I arethex and y co ordinates of the th point to be plated Inthis example the x co ordinate will be 7 Finally you need to supply the plotting symbol and a ttle E g CALL Grapher X Y Damped Oscillations where isthe platting symbol and Damped Oscillations isthe title The completemain program to draw this graph is then PROGRAM DrawGraph USE GraphMod IMPLICIT NONE INTEGER PARAMETER NPts 80 INTEGER I REAL PARAMETER i BE 3 1415927 REAL dt T REAL X NPts Y NPts T 0 dt Pi 20 0 DO I 1 NPts Y I EXP 0 05 T SIN T X I T T T dt END DO CALL SetWindow 0 0 4 Pi 1 0 1 0 real arguments CALL Grapher X Y Damped Oscillations END PROGRAM DrawGraph Figure 15 2 Output generated by Grapher 200 Damped Oscillations HHHHHH tt tt
226. by rangers of wildebeest between 1969 and 1972 to relieve pressure on the vegetation However since culling is indiscriminate among the non calf population it is easyto arguethattheterm amp I in equations 6 4 and 6 5 must d be replaced by gi d where accurately known k isthe tctal number culled in year k This number is The model run startsin 1969 k 1 with 1 3660 Y1 2240 1 1680 and 1 6440 These figures are fran the census Table 6 1 shows the tctal population predicted by the model compared with the census data The column headed Model I shows projections taking the annual culling into d 0 when running the model Note alsothat a particular projectio is based on the input inthe previous row e g if L 500 d 572 b 0 5 and g 4 the model predicts account whereas Model 2 assumes no culling by setting Co Y t w 12617 Table 6 1 Wildebeest model data and output Year 1969 1970 T97 1972 1973 1974 1975 The parameters g and b are realistic 19701972 were dry years inthe Park when lion killed regularly at waterholes This justifiesthe higher g and lower b values In subsequent yearsthe lion did not kill so freely since the improved vegetation and declining wildebeest population made the prey more difficult to find The same factors lead to a higher calf survival rete
227. cNo IOSTAT IF EOF 0 THEN PRINT A20 I3 Student END IF RecNo RecNo 1 END DO END SUBROUTINE DisplayRecords The subroutine UpDat takes care of updating a studert s record file contents Th nd of remember to initialize n F B OF Student EAD succeeded inthisexample only his single mark may be changed but obviously this can be extended to correcting spelling in his name amp c SUBROUTINE UpDate CHARACTER NameLen Item Copy LOGICAL Found Found false EOF 0 remember to initialize PRINT Update who READ A20 Item CALL StripBlanks Item RecNo 1 DO WHILE EOF 0 AND NOT Found READ 1 IOSTAT EOF REC RecNo Student IF EOF 0 THEN Copy Student Name CALL StripBlanks Copy leave his name as is IF Item Copy THEN Found true found him PRINT Found at recno RecNo Enter new mark CALL ReadIntCon Student Mark new mark WRITE 1 REC RecNo Student rewrite ELSE RecNo RecNo 1 EN D DO N PRIN D IF SUBR EN END IF EN D El N UpDate as student 1 s amp to FA 1S LOGICAI Li However this automatically gives LOGICAL the SAVE calls to UpDate This would give it the value TRUE making it impossible to executethe DO WHILI D IF IF OT T Found Item T a F
228. ce but write it only annually for 10 years use nested DO loops withthe outer loop for 10 years andthe inner loop for 12 months Note that after 10 years the balance is 3300 39 whereas if interest had been compounded annually at the rete of 12 per year the balance would only have been 3105 85 6 4 There are many formulae for computing 7 the ratio of a circle s circumference to its diameter The simplest is T TEESE which comes from the series 3 5 T 9 X X X arctan x x 76 aioe T whenx 1 Write a progran to compute 7 using series E6 1 Use as many terms in the series as your computer will reasonably allow start modestly with 100 terms say and re run your program with more and moreeachtime You should find thatthe series converges very slowly i e ittakes alct of terms to get fairly close to n Rearranging the series speeds up the convergence 1 1 1 sii 1x3 5x7 9xll 8 Write a program to compute 1 using this series instead You should findthat you need fewer terms to reach the sme level of accuracy that you got in a One of the fastest series for T is Z2 6 arctan a 2arctan A arctan 4 8 57 239 Use this formulato compute m Don t use the standard function ATAN to compute the arctangerts since that would be cheating Rather use the series E6 2 6 5
229. ch time Factorial is called separate copies are made of all the statements yet to be executed Finally the compiler finds a value of N 1 for whichit knows the value of Factorial soatlatit can beginto execute in reverse order the pile of statements which have been dammed up inside the memory This discussion illustrates the poirt that recursion should be used carefully While it is perfectly in order to use it in a case like this it can chew up huge amounts of computer memory and time TEshouldbe mentionedthat a RESULT clause may be used optionally when a function is not defined recursively in other words it is never wrong to have a RESULT clause Here itis shown witha nonm recursive version of Factorial IMPLICIT NON INTEGER I Gl DO I 1 10 PRINT I Factorial I END DO CONTAINS FUNCTION Factorial N RESULT Fact INTEGER Fact I N Fact 1 DO I 2 N Fact I Fact END DO END FUNCTION al Zz UF T When a subroutire calls itself directly the keyword RECURSIVE must also be used In the example below Factorial is rewritten as a recursive subroutine This is a littlemore sule IMPLICIT NON INTEGER F I Gl DO I 1 10 CALL Factorial F I PRINT I F END DO CONTAINS RECURSIVE SUBROUTINE Factorial F N INTEGER F N IF 1 THEN BS
230. ch are optional The following main program shows the irterface block required for Plonk together with some sample calls INTERFACE SUBROUTINE Plonk DumU DumV DumW DumX DumY DumZ OPTIONAL DumW DumX DumY Dumz END SUBROUTINE INTERFACE I eal Zz 0 m CALL Plonk A B Vie sl CALL Plonk A B C D 2 CALL Plonk A B DumX D DumY E DumZ F 3 Inthe first call onlythe non optional argumerts are passed Inthe second call the firsttwo optional arguments are required sothe list simply contains the first four arguments However the third call requires the last three optional arguments so they must be supplied as a keyword argument list the keyword in each case being the dummy argument name There may be no further positional arguments afterthe first keyword argument so the call CALL Plonk A B DumX D m Re E wrong would be invalid 100 Note that an explicit irterface inthe form of an interface body must be supplied when an external subprogram has optional arguments However since modules provide explicit interfaces this is not necessary inthe case of module subprograms with optional arguments Arrays as arguments This is more appropriate to discuss in Chapters 9 and 15 where we deal with arrays and matrices in some depth The SAVE attribute Local variables in a
231. ch time thr number of halvings or bisections required to find a name will be the smallest power of 2 that exceeds 1243 Le 11 since 2 1024 lt 1243 lt 2 2048 163 The smart way to findthe maximum number of bisections N required isto observe that N must be Suppose our studert database file contains NumRecs records alt N the smallest integer such that a 1243 i e such tha the required name would be the last one in the directory A linear search would involve examining all 1243 pages whereas a binary search requires you to J t N gt log 1243 Inthe worst possible case ook at only 11 pages together sorted so that the names are in alphabetical order We wouldliketo search for a given student e g in orderto be ableto view his marks and change them if necessary A binary search through the file must try to find the record number Mid of the required student s nam record numbers forthe search are Lo and Hi respectively Mid isthe average of these two values Successive bisections change the value of either Lo or Hi keeping the alphabetical posi Item The lower and upper bounds of the ion of Item between these bounds each time Since each bisection takes the integer part of Mid the starting value of Hi must be 1 more than the last record number or the last stu
232. commended E g LE BY 2 4 A C 107 20 30 Control passes to statements 10 20 or 30 according as B 2 4 A C is negative zero or positive IMPLICIT not recommended declares variables of a specified type according to their initial leter E g IMPLICIT INTEGER A X Z specifies integertype for all variables starting withthe letters A X Y and Z Itis betterto specify the type of each variable separtely in atype declaration statement IMPLICIT NONE suspends the implicittype rule whereby all variables withthe initial leter I to N inclusive are specified as irtegers with all cthers real This statement should appear in every program unit to force you to declare all objets specifically INCLUDE not recommended enables text from another file to be included in the source fil during compilation TE is n technically a Fortran statement and has the form INCLUDE filename 254 INQUIRE ascertainsthe status and attributes of a file t has three forms inquive by I O list inquire by file and inquire by unit Inquire by I O lis returnsthe length of an unformatted output record by means of the IOLENGTH specifier ag INQUIRE IOLENGTH reclen Student reclen can then be used to give the record length with the RECL specifi
233. ctions A function may be array valued If it is an external function it needs an interface block Array handling intrinsic functions There are a number of intrinsic functions which relate specifically to arrays The complete list isin Appendix C A sample is given here ALL X retums the value TRUE only ifall the elements of the logical array X are tne ANY X retumsthe value TRUE if any element ofthe logical array X istrue Otherwise it returns FALSE SUM X and PRODUCT X return the sum and product of the elements of the integer real or complex array X respectively Tn all these cases X can be an array expression 6g INTEGER DIMENSION 5 5 A REAL X 3 Y 3 yy A if any element gt 0 replace all by 1 0 A 1 if all elements 0 replace all by 1 Dot SUM X Y scalar product of X and Y Chapter 9 Summary e Arrays are useful for reoresenting and processing large amounts of data e An array is a Ollection of subscrigted variables with the same name e Members of an aray are called elements e The number of elemerts in an array is its size The size may be zero e Upper and lower bounds of array subscripts are specified withthe DIMENSION attribute inthe array type specification statement e An array subscrit may n fall otsice the bounds specified by DIMENSION e An array subscrit may be any valid numeric exp
234. ctor INTEGER DIMENSION A INTEGER I J T ALLOCATE Vector SIZE A allowed because Vector points Vector A DO I 1 SIZE A 1 DO J I 1 SIZE A 175 gt Vector J THEN IF Vector I J T Vector Vector J Vector I Vector I T END IF END DO END DO END FUNCTION Vector END A problem with this example is that there seems to be no way under FTN90 version 1 12 of deallocating Vector Arrays of pointers If you have been brought up on an exclusive diet of Fortran it may never have occurred to you to want tothink about an array of poirters Butthis could be useful if you wanted for example to set up an array of dynamic variables Now there is no direct way of declaring an array of poirters in Fortran 90 The obvious declaration which is n allowed would be REAL DIMENSION 100 POINTER X illegal This however would mean that X is a pointerto an array poirterto array of 100 real elements not an array of 100 poirters As we have seen the correct syntax forthe above declaration is REAL DIMENSION POINTER X This is more flexible and allows you to allocate the array size a runtime ALLOCATE X N The solutionto our problem isto create a type with a pointer component andthen to declare arrays of that type Representation of a triangular matrix For example each row of a lowertniangula
235. d PRINT Current Value is about to go just to make sure DEALLOCATE Current Current gt L alias of last remaining node END DO Tf you don t understand this perhaps you should also resort to drawing same diagrams Before you go any further you should put these pieces together in a working program to create a linked lig pirt it and dispose of it 13 3 Hidden Implementations of Abstract Data Types One of the advantages of modules is that the details of the implementation of an abstract data type may be hidden from the user of a module Allthe user is supplied with isthe name of the datatype and subprograms for manipulating it This way the details of the implementation inthe module may be changed without affecting any code that uses the module To illustretethis most important principle two modules are given inthis section One implements a list of integers as a linked list the other implements the list as a dynamic array The only change required in the driving main program isthe name of the module used The linked lit implementation is inthe module ModLink It is very similar to the example in Section 13 2 but has some importart differences which are discussed below MODULE ModLink Implementation of abstract data type as a linked list IMPLICIT NONE PRIVATE NODE TYPE NODE INTEGER Value TYPE NODE POINTER Next END TYP
236. d write out the larger of the two with a suitable message 4 6 Write a program to read a set of 10 numbers from a file and write out the largest number in the set Now adjust the program to write out the position of the largest number inthe set as well e g if th data is on separate lines in the file the output should be 9 largest number and 4 fourth number in the set 4 7 Write aprogram to canpute the sum of the series 1 1 2 1 3 1 100 The program should writethe current sum after every 10 terms i e the sum after 10 tems after 20 terms after 100 terms Hint the intrinsic function MOD N 10 willbe zero only when N isa multiple of 10 Usethisin an IF statement to write the sum after every 10thterm Answer 5 18738 after 10 tems 46 Chapter 5 Decisions Chapter 5 Introduction 5 1 The IF Construct e Bending moment in a beam e Top of the class ELSEIF e The IF Construct in General e Nested IFs e DOs andIFs ogical constants ogical Expressions ogical operators e ogical variables e Simulation of a switching circuit e Bit manip ion functions 5 3 The Case Construct 5 4 The Go To Statement Chapter 5 Summary Chapter 5 Exercises Chapter 5 Introduction Apart from its ability to add numbers extremely quickly a computer s other major property isto be
237. d concatenation CA DAT 7 E AND _TIMECHARACTER 10 DATE TIME PRETTY TIMI T Gl PRINT DATI DATE AND _TIME DATE TIME Gl PRETTY TIME TIME 1 2 TIME 3 4 TIME 5 10 PRINT PRETTY TIME END Output 36 19930201 15 47 23 0 Chapter 3 Summary e A DO loop is used to repeat ablock se of statements e The IF THEN ELSE construct enables a program to decide between alternatives e The IF statement is a shorter form of the IF construct e 6 Character constarts are strings of characters enclosed in apostrophes or quctes e Named constan e Variables may be ini e Each of the int kinds ts parameters may nct be changed in a program ialized in a type declaration trinsic data types has a default kind and a system dependert number of other e The kindtype parameter associated with a datatype is an integer which evaluatestothe kind of that data type e The value of kind type parameters is system dependert e Charaters may have two type parameters in theirtype declarations one for length and one for kind e Complex numbers and arithmetic are supported by the COMPLEX intrinsic type e Complex constants must be enclosed in parentheses for input with READ e Trtrinsic builtin functions may be used to compute a v
238. d of get sligt 3 15 the year But if interest is compounded at the rate of 1 monthly i e 1 12 of the annual rate you ly moreirterest inthe long run Adaptthe program Invest in Section 3 1to computethe balance after a year of compounding interest inthis way The answer should be 1126 83 Evaluate the formula for this result separately as a check 1000 times 1 01 A plumber opens a savings account with 100 000 at the beginning of January He then makes a deposit of 1000 at the end of each month forthe next 12 months starting at the end of January Interest is calculated and addedto his account atthe end of each month before the 1000 depositis made The monthly interest rete depends onthe amount A in hisaccourt atthetime when irterest is calculated inthe following way A lt 110 000 1 110 000 lt A lt 125 000 1 5 A gt 125 000 2 Write a program which displays foreach ofthe 12 months under suitable headings the situation at the end of the month as follows the number of the month the interest rate the amount of interest and the new balance Answer values in the last row of output should be 12 0 02 2534 58 130263 78 3 16 formula 197273000 0 03134 t 1913 25 e P t Tt has been suggested that the popul ion of the United es may be modelled by th where isthe date in years Write a progran to co
239. data is presented by rows e As an altemativetothe DATA statement the arrays could have been read from the keyboard or a file eg assuming the cata to be in row order READ C I J J 1 3 I 1 3 e An array constructor may only be used to initialize a one dimensional array However the irtrinsic function RESHAPE may be usedto initialize a multidimensional array from an array constructor as shown in Chapter 9 e Fortran 90 provides a neater way of calculating the tctal cost of the transport scheme above Since the intrinsic operetors when appliedto arrays operete on all elements of the array the OLX operation C X will retumthe 3 3 array with elements Y The intrinsic function SUM returns the scalar sum of allthe elements of its array argument Therefore the single statement SUM C X will calculate the tctal cost Try it out 15 2 Graphs Without Graphics Standard Fortran 90 does not provide outputto graphics devices such asa PC graphics screen The module GraphMod described inthis sectim enables you to draw a rough graph of any function on the standard outouk device eg the PC text screen or piten As an example suppose you want to draw 0 05t os in y t e eee range Ost the module which you needto call The the graph of the function 4T in steps of m1 20 There are two su
240. de READ 10 I J 10 FORMAT I1 reads two values 1 and 3 from the input records 12 34 A format specification without parentheses may therefore be thought of as a template of how the compiler sees the entire I O record 131 b 0 1 However if a format specification contains items in parentheses when the format is exhausted a new record is taken and format control reverts to the left parenthesis corresponding to the second last right parenthesis including a possible repeat count outside the parentheses This is called reversion E g in 10 FORMAT F5 0 2 F6 1 3 F7 2 F8 3 new records tat a 2 F6 1 Carriage control Fortran s formatted output statements were originally designed for line prirters For output to such devices the first character of each record is used for carriage control an old fashioned word from the days of mechanical typewriters There are four options olank start a new line remain on same lire overprint skip a line advance to the beginning of anew page A blank inthe firs column effectively means no action istaken so itis good practiceto make surea blank is sent asthe first character e g by starting all format specifications with T2 begin writing in position 2 Otherwise for example printing an integer under FORMAT I3 will cause a page throw every time the irteger is inthe range 100 1
241. dent String 154 CHARACTER String TYPE Student _Type Student Student Name String END SUBROUTINE ND MODULE m An interface block using the keyword ASSIGNMENT is required to overload the assignment operator with these two subroutines tis shown here inthe module although it could also be inthe main program A complete main program is then USE StudentMod TYPE Student _Type Student Student _Type Bloggs 50 CHARACTER 20 StuName Student Smith JR assigns only the name in one direction StuName Student assigns only the name in the other direction PRINT A20 F6 0 Student PRINT StuName END Note that subroutines are needed to redefinethe assignment operator Other operators are redefined with functions as we shall see now Assignment for irtrinsictypes may n be redefined Defined operators overloading Operators may be defined for derived types in a similar although n identical way Consider the following example adapted from the FTN90 Reference Manual The module IntegerSets defines atype SET similartothe set type of Pascal Variables of thistype can be constructed from the integers with the function BuildSet A set membership operator IN is defined e g 1 IN S1 returns TRUE ifthe irteger Iisa member of the set S1 The operator is overloaded with the operation of set intersection
242. dent can never be found The maximum number of bisections required NumBis is found as described above This requires computing a logarithm to the base 2 in terms of the natural logarithm The formula forthis is 10824 log ea log e2 The coding forthe binary search is as follows SUBROUTINE BinSearch NUnit Item Binary Search for string Item through all StudentRecord 164 m 2 records on NUnit Po sn Record number of match returned in Posn if no match found CHARACTI GAN R Item INTEGER Count EOF Hi Lo Mid NumBis LOGICAL Found TYPE StudentRecord Student which is zero NumRecs NUnit Posn find the number of records NumRecs EOF 0 NumRecs 0 DO WHILE EOF 0 READ NUnit REC NumRecs 1 IOSTAT IF EOF 0 THEN NumRecs NumRecs 1 END IF END DO NumBis INT LOG REAL NumRecs LOG 2 Count 0 Found false Posn 0 Lo 1 Hi NumRecs 1 DO WHILE NOT found AND Count NumBis Mid Hi READ NUnit REC Mid Student Student IF Item Student Name THE Found ELSE END IF END DO IF Found Tio 2 Name TRIM Student true ELSE IF Item lt Student Name Hi Mid Lo Mid Count Count 1 Posn Mid F D SUBROUTIN py THI EOF oky oe ae one of bisecti
243. dents test results or to solve a system of linear equations To avoid an enormously clumsy program where perhaps hundreds of variable names are needed we can use subscripted variables or arrays These may be regarded as variables with componerts rather like vectors or matrices They are written in the normal way except that the subscricts are enclosed in parertheses after the variable name e g KS VL t 22 N Fortran 90 has an extremely powerful set of array features which Fortran 77 users will be both surprised and delighted to discover 108 9 1 Mean and Standard Deviation To illustretethe basic principles let s computethe sample mean and standard deviation of a set of N observations The mean is defined as X x I 2 Il where X isthe ith observation The standard deviation s is defined as s dx X The next program computes theset wo quantities from data read from the disk file DATA The first item of datain the file isthe value of N Thisis followed by exactly N observations all on separate lines IMPLICIT NONE INTEGER I N REAL Std 0 REAL DIMENSION 100 X REAL XBar 0 OPEN 1 FILE DATA READ 1 N DO I 1 N READ 1 X I XBar Xbar X I END DO XBar XBar N DO I 1 N Std Std X I XBar 2 END DO Std SQRT Std
244. differert kind parameter values the result has the kind parameter of the operand with the greater precision Real kinds The functions KIND and HUGE described above alsotake real arguments With realtype an attempt to go beyond HUGE causes an overflow error The function SELECTED REAL KIND P R returmsthe kind parameter of the realtype with precision at P number of significant decimals and an exponent range of at least 10 to 10 if available P and R must be integers The kind of a zeal constant may be specified inthe same way as an irteger consart The standard requires that in additionto a default real kind there must be at least one real kind with a greater precision than the default this corresponds to the now obsolete DOUBLE PRECISION type of earlier versions If this more accurete represertation has for example a kind parameter value of 2 the AIDS program of Chapter lmay be amended by replacing the REAL statement with REAL KIND 2 A number of cases and the numeric assignment with RS L746 CT A198 v2 2 3 Note that to get a significantly different answer the expression must be coerced into the stronger type Run this to see how the answer differs Further functions relating to real kind are described in the appendices Character kinds The default kind of character constart include
245. dynamic with the ALLOCATABLE attribute In particulary a one E dimensional array may be specified thus REAL DIMENSION ALLOCATABLE X Although its rank is specified it has no size until it appears in an ALLOCATE statement such as ALLOCATE X N When itis no longer needed it may be ceallocated DI KALLOCATE thus freeing u p the memory used The following program extract shows how to use allocatable arrays as these beasts are called to read an unknown amount of data which unfortunately must be supplied one item per line because of the way READ works REAL DIMENSION ALLOCATABLE xX OLAX REAL A INTEGER IO N ALLOCATE X 0 size zero to start with 113 N 0 OPEN 1 FILE DATA DO READ 1 IOSTAT IO A IF 10 lt 0 EXIT N NU4 1 ALLOCATE OldX SIZE X Oldx X entire array can be assigned DEALLOCATE X ALLOCATE X N X OldX X N A DEALLOCATE Oldx END DO PRINT X I I 1 N We would lketo be ableto increase the size of X for each value read However before X can be allocated with a larger size it must be deallocated losing all the previous data read So another dynamic array OldX must be used totake care of this Note the following importart features e an array may have zero size t
246. e A module subprogram has exactly the same form as an extemal subprogram except that the FUNCTION or SUBROUTINE keyword must be present in the END statement t has access to all other entities in the module including all variables declared in it Note that a module subprogram may contain its own irternal subprograms module subprograms relative to these program We have now encountered all three types of program unit The nesting of internal external and units is illustreted in Figure 8 2 A module may USE cther modules although it may not access itself indirectly through a chain of modules only use earlier ones USE statements in different modules No ordering of modules is required by the standard In developing libraries of modules however you shouldtryto design a hierarchy to ensure that later Since a module may contain declaration statements which are accessibleto all host program units global variables may be declaredinthis way for use by all hosts accessing the module This feature is particularly useful for making more complicated declarations such as those for derived types globally available Tn particular interface blocks may be groupedtogetherirto modules As an example consider again the external subroutine SWOP of Section 8 3 Es irterface could be ina module MyMod Figure 8 2 Subprograms and pr
247. e DO WHILE EOF 0 READ 1 REC RecNot l1 IOSTAT EOF IF EOF 0 THEN read succeeded so RecNo RecNo 1 only increment RecNo her END IF END DO RecNo RecNo 1 next record to write Student StudentRecord a 0 satisfy DO WHILE DO WHILE VERIFY Student Name NameChars 0 PRINT Name any non letter non blank to end READ A20 Student Name IF VERIFY Student Name NameChars 0 THEN PRINT Mark CALL ReadIntCon Student Mark WRITE 1 REC RecNo Student cNo RecNo 1 I R ND IF D 0 Fl EN O ND SUBROUTINE AddRecords El Fortran 90 unfortunately has no way of determining the number of records in a file her than by reading past allofthem The first DO WHILE sets RecNo tothe number of records inthe file Note that a READ with no input lit skips past a record this saves time EOF must be initialized to zero on entry to the subroutine because it is a global variable so it will usually have a non zero value from the lasttime the end of file was encountered This provides a good reason for declaring EOF locally to force you to initialize it correctly A DO WHILE loop accepts students names from the keyboard In this example it is assumed that names will consist only of letters or blanks e g between the surname and initials So any character otherth
248. e a variety of algorithms under the general name of Runge Kutta which can be used to integrate systems of ordinary differential equations The fourth order formula is given below for reference A derivation of this and the other Runge Kutta formulae can be found in most books on numerical analysis Runge Kutta fourth order formulae The general first order differential equation is dy dx f x y y 0 given 16 14 The fourth order Runge Kutta estimate y at x h is given by y y k 2k 2k k 6 where 237 k hf x y k hf x 0 54 y 0 5k k hf x 05h y 0 5k k hf x h y k Systems of differential equations a predator prey model The Runge Kutta formulae may be adapted to integrate systems of first order differential equations Here we adapt the fourth order formulae to integrate the well known Lotka Volterra predator prey model dx dt px qxy 16 15 dy dt rxy sy 16 16 where x t and y t are the prey and predator population sizes at time t and p q rand s are biologically determined parameters We define f x y and g x y as the right hand sides of Equations 16 15 and 16 16 respectively In this case the Runge Kutta estimates x and y at time t h may be found from x and y at time t with the formulae x x k 2k 2k k 6 y y m 2m 2m m 6 where k hf x y m hg x y k hf x 0 5k y 0 5m m hg x 05k y 0 5m k hf x 0 5k y
249. e hav mdv dt mg pv where m is his mass g the acceleretion due to gravity v his velocity and p is a constant of proportionality Dividing by m we can rewrite this as dv dt g kv 16 5 k p m_ where Equation 16 5 isthe differential equation describing the motion of the skydiver under gravity The constant k varies with shape and mass and may be found experimentally from the terminal velocity of the falling object This terminal velocity r is reached when the object stops accelerating and may be found by equating the right hand side of Equation 16 5 to zero Thus vr y4g k For a man wearing an unopened parachute k is found to be about 0 004 in MKS units Before we proceed withthe numerical solution of Equation 16 5 we should notethat this particular differential equation can be solved analytically since it is of the type called variable separable a C oe ere 4 16 6 este eg kO a 0 a v 0 l Euler s method for solving Equation 16 5 numerically consists of replacing the derivative onthe left hand side with its Newton quctiert and equating this to the right hand side as it stands After a slight rearrangment of terms we get v t h v t ilg kv t 16 7 If we divice up the time period t irto n intervals
250. e intializedinthis way may be changed laterinthe program Although more complicated expressions are allowed when initializing it is recommended for stylistic reasons that initialization be restricted to simple assignments as shown above Although the variables X INTEREST and LETTER have been declared inthe program fragment above they are as yet undefined asthey have no value You should avoid referencing an undefined variable A variable may be defined in a number of ways e g by initializing it A above or assigning a value to it as in other examples we have seen A variable may also be given an initial value in a DATA statement afterbeing declared e g REAL A B INTEGER I J DATA A B 1 2 1 J 0 1 A name ina program must be unique For example if a program is named MONEY an attempt to declare a variable of the same name will cause an error The variables described here are scalar because they can hold only a single value Implicit type rule Earlier versions of Fortran had what was called an implicit type rule Variables starting with the Idters Ito N inclusive were automatically specified with irtegertype while variables starting with any other letter were automatically specified real This unhelpful rule still applies in Fortran 90 by default to ensure compatibility of code
251. e key file PRINT DO Num 1 TotRecs use sorted keyfile to write order of merit READ KeyFile REC Num KeyVar read key file for RecNum READ StuRecFile REC KeyVar RecNum Student read RecNum PRINT A20 13 Student print merit list END DO CLOSE 1 CLOSE 2 CONTAINS SUBROUTINE Key Sort X TYPE KEY DIMENSION INTENT INOUT X list TYPE KEY Temp temp for swop IF X J KeyField lt X J 1 KeyField THEN 166 END SUBROUTIN ND Gl m If a key file is set up with names as the key field it can be sorted on the names with sligt adjustmentsto Key Sort A binary search for a name canthen be conducted on the key file with reference to the original database for that sudert s mark s if necessary 12 5 Hashing The program in this section does not use derivedtypes however it arises naturally from the earlier discussion of searching One problem with a binary search is that the items must be sorted This means that if additional items are added to the list the entire list must be resorted before a search can be conducted The method discussed in this section does not require the items to be sorted and is one of the most efficiet methods of searching hashing If you are a programming novi you might like to skip this section and come back to it later Suppose we have an array Names asi
252. e may want to model or represent quantitatively are usually those in which the variables change in time e g biological electrical or mechanical systems If the changes are continuous the system can often be represented with equations involving the derivatives of the dependent variables Such equations are called differential equations The main aim of a lot of modelling is to be able to write down a set of differential equations that describe the system being studied as accurately as possible Very few differential equations can be solved analytically so once again numerical methods are required We will consider the simplest method of numerical solution in this section Euler s method Euler rhymes with boiler We will also consider briefly how to improve it Vertical motion under air resistance Euler s method To illustrete Euler s method we will take an example from Newtonian dynamics of motion under gravity against air resistance Suppose a skydiver steps out of a hovering helicopter but does not open his parachute for 24 seconds We wouldliketo find his velocity as a function of time during this period Assuming air resistance cannot be neglected ask any skydiver he falls subject tot wo opposing vertical forces gravity acting downward and air resistance acting upward The air resistance force is assumed to be proportional to the square of his velocity this is fairly accurate Applying Newton s second law to the skydiver w
253. e program is then simply PROGRAM Leslie USE MatMult PLICIT NONI Z J E Gl AL DIMENSION 3 3 L Leslie matrix AL DIMENSION 3 X Population vector TEGER T ao ll L A5 4A14 Month Young Middle Old Total X L ex PRINT I5 4F14 1 T X SUM X END DO x x END PROGRAM Leslie The output over a period of 24 months is Month Young Middle Old Total 214 1 12 0 0 0 0 0 12 0 2 0 0 4 0 0 0 4 0 3 36 0 0 0 2 0 38 0 4 24 0 12 0 0 0 36 0 5 108 0 8 0 6 0 122 0 6 144 0 36 0 4 0 184 0 22 11184720 0 1864164 0 466020 0 13514904 0 23 22369716 0 3728240 0 932082 0 27030038 0 24 44739144 0 7456572 0 1864120 0 54059836 0 Note how A format may be used to g amp headings inthe right place TE so happens that there are no fractional rabbits in this example If there are any they should be kept and not rounded and certainly not truncated They occur because the fertility rates and survival probabilities are averages Tf you look carefully at the output you may spot that after some monthsthetctal population doubles every month This factoris calledthe growth factor andisa property of the particular Leslie matrix being used forthose who know about suchthings it sthe dominant eigenvalue of the matrix The growth factor is 2 inthis example but ifthe values inthe Leslie matrix are changed the long term growth factor changes too try it
254. e same program may not have the same name neither may they have the names of any entities declared in the program unit There is a separate scoping rule forthe DO variable of an implied DO Chapters 9 and 10 it extends only tothe imp led DO 98 8 7 Arguments There are a number of important properties of subprogram arguments which are summarized in this section for ease of reference We first look at precisely how actual arguments are passed to subprograms This happens in two fundamentally different ways by reference or by value It is necessary to understand clearly the difference between these two mechanisms Reference arguments If the actual argument is a variable it is passed by reference The term variable includes an array name an array element an array substring a structure component or a substring all these concepts are discussed later What actually happens in this case is that the address in memory of the actual argument is passed to the subprogram and the corresponding dummy argument is made to reside at the same memory address In other words the actual argument and dummy argument both refer to the same memory location As a result any changes made to the dummy argument are reflected in the actual argument on return to the calling program You can therefore think of the value of the actual argument being copied to the dummy argument on call and the value of the dummy argument which may h
255. ealtime clock Intrinsic Procedures TE is helpful to categorize intrinsic procedures as follows although the descriptions below are grouped somewhat differently far convenience of reference e Elemental procedures may be appliedto scalars or arrays When applied to arrays the operation is performed on each element of the array Arguments may be real or complex unless otherwise stated or unless the context clearly requires otherwise Arguments must generally be of th same type e Inquiry functions properties of their arguments e Transformational functions usually have array arguments and an array result depending in some way onthe elements of the arguments e Non elemental subroutines Descrictions below are given with dummy arguments so that optional arguments indicated thus may be passed using the dummy argument names as keywords 265 Results are usually returned in the default kind unless the KIND keyword is used where appropriate Trigonometric functions assume arguments are in radians and return radians Almost all of the procedures are functions To highlight the few that are subroutines the keyword CALL has been included inthe descrigtion C 1 Elemental Numeric Functions Note that the arguments may be real or complex scalars or arrays unless otherwise stated ABS A absolute value of integer real ar complex A ACOS X inverse cos
256. ed ina string delimited by the cther sat as in Jesus said Follow me Alternatively the delimiter should be repeated as in Pilate said What is truth A character string may be empty i e or The number of characters in a string is called its length An empty string has a length of zero Character variables The statement CHARACTER LETTER declares LETTER to be a character variable of length 1 i e it can hold a single character Longer characters may be declared as inthe program Final_Mark 30 CHARACTER Len 15 Name This means that the character variable Name can hold a string of up 15 characters An alt ive form of the declaration is CHARACTER Name 15 Character constarts may be assigned to variables inthe obvious way Name J Soap On an input record the quote or apostrophe delimiters are not needed fora character constart ifthe consart does n cortain a blank comma or slash Sincethe names in the example above contain commas and blanks delimiters are needed in the input file 3 4 Named Constants Inthe program Vertical in Chapter 2 the declaration statement REAL PARAMETER G 9 8 was used to declare G as a named constant or parameter The effect ofthis is that G may not be changed later in the program any attempt to do so will generate an error message
257. eleration due to gravity The horizontal and vertical digolacements are given by the formula 34 x utcosa y ut sina gt 2 f V V V f The velocity has magnitude V such that Y where its horizontal and vertical V components Vy ad aegivenby V ucosa V u sina gt and V makes an angle with the ground ie VOS The program is PROGRAM Projectile IMPLICIT NONE REAL PARAMETER g 9 8 acceleration due to gravity REAL PARAMETER Pi 3 1415927 a well known constant REAL A launch angle in degrees REAL T time of flight REAL Theta direction at time T in degrees REAL U launch velocity REAL V resultant velocity REAL Vx horizontal velocity REAL Vy vertical velocity REAL X horizontal displacement REAL Y vertical displacement READ A T U A A Pi 180 convert angle to radians X U COS A T Y U SIN A T g T T 2 Vx U COS A Vy U SINC A T V SQRT Vx Vx Vy Vy Theta ATAN Vy Vx 180 Pi PRENTA sc Mag Xo Pig eee IY PRINT Vr Vy Theta Theta END Tf you run this program with the data 45 6 60 you will see from the negative value of 0 that the projectile is coming down The argument of a function may be any valid Fortran expression of appropriate type including another function So V could have been computed directl
258. ell known fact that the definite integral of a function FO between the limits x a and x b is equal to the area under f x bounded by the x axis and the two vertical lines x a and x b So all numerical methods for integrating simply involve more or less ingenious ways of estimating the area under f x The Trapezoidal Rule The method we will use hereis calledthe Trapezoidal or Trapezium Rule The area under f x is divided into vertical panels each of wicthh calledthe step length Ifthere are n such panels then nh b a FE n b a h If we join the points where successive panels cut S we can estimate the area under f x as the sum of the area of the resulting trapezia If we callthis approximation tothe irtegral S then h n 1 2 Al fla 2S fs izl 16 3 mes AR n eaae Traa als a a notes i f x dx We can include a function Trap to evaluate an irtegral in this way in our module NumUtils FUNCTION Trap A B H Fung INTERFACE FUNCTION Fung X FAL Fung EAL INTENT IN X END FUNCTION Fung D INTERFACE AL Trap A T RI RI H INTENT IN A B H EGER I N N NINT B A H 229 DO I 1 N 1l using notation defined END DO m ND FUNCTION Trap in text Trap Trap Fung A I H Trap H 2 Fung A Fung B 2 Trap Es dummy argument Fung
259. emal subprogram has scope in all subprograms which it corttains The scope of a name declared in an internal subprogram extends throughout that internal subprogram only and does not extend to other irternal subprograms It follows that the scope of a name declared ina program or subprogram does not include any internal subprograms in which itis redeclared The scope of the name of an internal subprogram as well as its number and type of arguments extends throughout the containing program or subprogram and therefore throughout all her irternal subprograms The scope of a name declared where the name is that of a variable or a subprogram now ina module extends to any program units that use the module but obviously excludes any internal subprograms in which the name inthe case of a variable is redeclared Having described the basic elements of scope it is helpful to make the concept more precise by defining a scoping unit Figure 8 3 Some implications follow fi this definiticn e Entities declared in differert scoping units are always different even if they have the sam names and properties e Within a scoping unit each named data object subprogram derivedtype named construct and namelist group must have a distinc name withthe exception of generic names of subprograms e The names of program units are global so program units inth
260. empts to improve an estimate of the root if Me is an approximation to the roct the next approximation Xis is given by E 1 f e where f x is d dx A structure plan to implement Newton s method is 1 Read in tarting value Xo and required accuracy e 2 While f x 2 Xi Xk f x f x Print x and f Sexi 3 Stop repeat up to k TE is necessary to limit step 2 since the process may not converge 3 A program using Newton s methodto solve the equation X 3 0 tart 20 say 2 ing with Xo zis given in Chapter 8 If you run it you will see that the values of x converge rapidly to the root As an exercis try running the program with different starting values of Xo algorithm always converges to see whether the Also try finding a non zero roct of 2x tan x using Newton s method You might have some trouble withthis one If you do you will have demonstreted the one serious problem with Newton s method it converges to a root only if the starting guess is close enough Since close enough depends on the nature of f x and on the root one can get into difficulties her The only remedy is some intelligent trial and ernor work on the initial guess this is considerably easier if you sketch f x carefully Ifthe method failsto find a rock you should use the Bisection method discussed Complex root
261. en below e You should make liberal use of comments both at the beginning of a program unit or subprogram to describe briefly what it does and any special methods that may have been used and also throughout the coding to introduce different logical sections Any restrictions on the size and type of datathat may be used as input should be stated clearly in the commerts e g maximum sizes of arrays e The meaning of each variable should be described briefly in a comment atits declaretion You should declare variables systematically eg in alphabetical order by type e Subprograms should be arranged in alphabetical order with at least one blank line between them e Blank lines should be freely used to separate sections of coding e g before and after loop structures e Coding inside structures Loops decisions etc should be indented a few columns to make them stand out e Blanks should be used in statements to make them more readable eg on either side of operators and equal signs after commas e However blanks may be omittedin places in complicated expressions wherethis may make the structure clearer e FORMAT statements should be grouped together e The GOTO statement shouldnever be used under any circumstances e You shouldtry to avoid breaking out of structures inthe middle eg withCYCLE or EXIT e St emerts which generate an obs
262. en the compiler generates a call to an external subprogram this information is not available andthe subprogram irterface is said to be implicit We have seen that the EXTERNAL statement in the calling program is sufficient to supply the compiler withthe name of the external subprogram and this enables it to be found and linked However the irterface is sill implicit and in more complicated cases such as with optional or keyword arguments as discussed below further information is required for a satisfactory interface Fortran 90 has a mechanism called an interface block which enables an explicit interface to be made The general form of an irterface block which must be placed in the scope of the calling program is INTERFACE interface body ND INTERFACE m where the interface body could be an exact copy of the subprogram header declarations of its arguments and results and its END statement However the names of the arguments may be changed and other specifications may be included e g for a local variable although not DATA or FORMAT statements or irternal subprograms T he calling program for the external subroutine SWOP above could be rewritten with an interface block as fallows IMPLICIT NONI Gl INTERFACE SUBROUTINE SWOP X Y REAL X Y UBROUTINE ERFACE T zal Z
263. ent which is a poirterto a dynamic array also inaccessibletothe Insert uses the technique of Chapter 9 to increase the size of a dynamic array by one element each time a new value is added PrintList uses an alias P to refer to the dynamic array purely for convenience Note that the TARGET attribute of the derived type L is conferred on its component To use this impleme ion all you have to do is to change the second line of the main program TestList to USE ModArray We have seen inthis section t dynamic array implementation the user Type definitions and hat modules with derived types can hide implementation details from coding inthe module procedures may be changed without affecting any code which uses the modul es Chapter 13 Summary e A poirter variable has ths POINTER attributs and may poirtto be an alias of a variable of the same type which has the TARGET attribute e An alias is simply ancther name for an object e Poirter assignment gt setsup or changes an alias e Ordinary assignment of pointer variables operetes on their aliases e A poirter may be in one of three states undefined null ar associated The NULLIFY statement puts a pointer into the null state This may be tested for with the ASSOCIATED irtrinsic function e The ASSOCIATED irtrinsic function ascertains whether a pointeris an a
264. er of an OPEN statement The cthertwo forms are INQUIRE FILE filename spec list by file INQUIRE UNIT u spec list by unit where filename and u arecharacter and irteger expressions respectively spec listisalist of o tional specifiers Their names and values returned are char means character EXIST logical TRUE if it exists FALSE otherwise OPENED logical TRUE if connected FALSE otherwise NUMBER integer value of unit number connected or 1 if no unit is connected NAMED logical TRUE if file has a name FALSE otherwise NAME char returns name if file has a name ACCESS char SEQUENTIAL DIRECT or UNDEFINED if there is no connection SEQUENTIAL and DIRECT char YES NO or UNKNOWN depending on allowed mode of access FORM char FORMATTED UNFORMATTED or UNDEFINED RECL integer maximum record length allowed NEXTREC integer number of most recent record read or written BLANK char NULL or ZERO depending on whether blanks in numeric fields are interpreted by default as null fields or zeros POSITION char REWIND APPEND ASIS or UNDEFINED see OPEN ACTION char READ WRITE READWRITE or UNDEFINED READ WRITE and READWRITE char YES NO or UNKNOWN DELIM char APOSTROPHE QUOTE NONE or UNKNOWN see OP PAD char
265. et of lines where that name or label may be used unambiguously Scoping rules for labels and names are different Scope of labels The only approved use of labelsinthis book isin FORMAT statements which we will only discuss in detail in Chapter 10 However labels can also be used in conjunction with the notorious GOTO statement and to end a DO loop although such practices are n recommended Figure 8 3 A scoping unit scoping unit is one of the following Metcalf and Reid A derived type definition Chapter 12 A subprogram interface body excluding any derived type definitions and interface bodies contained within it or program unit or subprogram excluding derived type definitions interface bodies and subprograms contained within it Each subprogram internal or external has its own independert set of labels So for example the same label may be used in a main program and several of its intemal subprograms without ambiguity The scope of a label therefore is a main program or a subprogram excluding any irternal subprograms that it contains Scope of names The scope of a name declared in a program extends from the PROGRAM statement to the END statement and does not extend to any external subprograms that may be invoked A name declared in a subprogram has scope from the subprogram s header to its END statement Ik follows that a name declared ina main or ext
266. eturns 1 8 NINT A KIND nteger raes to A REAL A KIND function converts to ral SIGN A B absolute value of A times sign of B SIN A sine SINH A hyperbolic sire 266 SORT A square mod TAN A tangert TANH A hyperbolic tangert C 2 Elemental Character handling Functions Compilers must support the ASCII collating sequence but may also support her collating sequences ACHAR I character with ASCII code I for I inthe range 0 127 see Appendix D ADJUSTL STRING string of same length by changing leading blanks irto trailing blanks left justify ADJUSTR STRING string of same length by changing trailing blanks into leading blanks rigt justify CHAR I KIND character in position I of the system collating sequence with given kind TACHAR C ASCII code of character C see Appendix D ICHAR C position of character C inthe system collating sequence INDEX STRING SUBSTRING BACK starting position of SUBSTRING as a substring of STRING or zeroifit does not occur The position of the first or last substring is returned according as BACK is absent FALSE or TRUE cal AN TRIM STRING length of STRING without trailing blanks GE STRING A STRING _B TRUE if STRING_A follows STRING B inthe ASCII sequence or
267. exit the loop is appropriate here since the initial term might be small T ions for terminating the loop Conseque tly an IF is required after the DO to establish which condi ed ion was satis You may be tempted to use a DO enough with parameters and an EXIT to escape if Term gets small DO I 1 MaxTerms IF ABS Term lt Err EXIT END DO Although this works perfectly well it is definitely not recommended some progranmers will q itt finitely disagree The reasons are as fol clear at the very top of the loop after a cursory glance you might t lows My objection isthat all conditions for exit are not hink it is a deterministic loop But you may argue Iam spl 72 ng hairs at fter all the second condition for exit is inthe very next line But after a few months you might introduce further conditions later inthe block The trouble is that this innocent looking structure allows for ad hoc amendments later at which stage the programmer might easily lose track of what all the conditions for exit are The principleis all conditions for exit should be stated clearly in one place at the top or the end of the loop 6 6 Taking Stock Modelling a Population of Gnus Once you have mastered loops a great vista of interesti
268. face block The following code uses this fined in th E would be more elegart to rede C A B Ther isa complica arrays as we have seen and anir fine the intrinsic operator so that ion here though because intrinsic multipli trinsic operation may not be rede module to test the two forms of matrix multiplication USE MatMult REAL A 2 3 RESHAPE 1 3 2 4 1 2 2 3 REAL B 3 2 RESHAPE l 2 1 0 2 3 3 2 REAL D 2 2 RESHAPE 1 3 2 4 2 2 REAL X 2 2 3 REAL C 2 2 C A x B matrix times matrix PRINT 2F3 0 C I J J 1 2 I1 1 2 X D x X matrix times vector PRINT 2F3 0 X t one could write statements like ion is defined for ned The solution isto define a new type to reoresent matrices and then to overload the operator 1 M2 M3 de fined inthis way can then be written If atype TYPE MATRIX REAL Elt END TYPE MATRIX is defined matrices can be declared with TYPE MATRIX DIMENSION 2 2 M A function which explicitly multiplies two matrices FUNCTION MatTimesMat A B TYPE MATRIX DIMENSION A TYPE MATRIX DIMENSION SIZE A 1 INTEGER I J EM EM SIZE A 2 DO I 1 SIZE
269. fferential equations PDEs is a vast subject Space only permits one example which serves two important purposes It demonstrates a powerful method of solving a class of PDEs called parabolic It also illustrates a method of solving tridiagonal systems of linear equations Heat conduction Y The conduction of heat along athin uniform rod may be modelled by the parti GU OU pe eae a x 16 17 where U x f isthe temperature distributio a distance x from one end of the rod at time It is assumed that no heat is lost from the rod along its length l differential equation 242 Half the battlein salving PDEs is mastering the notation We set up a rectangular grid with step lengths of h and k inthe x and t directions respectively A general point on the grid has co ordinates x th y jk X A concise notation for U x amp Yj isthen simply U Now b is of course the exact solution of the PDE Exact solutions can only be found in a few special cases we wart a general method for finding approximate solutions This is done by using i an Ujj truncated Taylor series to replace the PDE by a finite difference scheme We define Y asthe X V solution of the finite difference scheme at the grid point We now attempt to find numerical solutions for which will therefore be our approximation to the e
270. file can be created first if necessary It can also change some properties of a connection The general form is OPEN UNIT u spec list where u isthe unit number The specifiers in spec list are char means character IOSTAT irteger returns zero if the statement successfully executes and a positive value otherwise 257 ea w R integer constart label of statement to which control passes if an eror occurs FILE char provides file name ifthis specifieris omitted the STATUS specifier must be set to SCRATCH andthe file is deleted when the connection is closed STATUS char OLD file must already exist NEW file must not exis but is created REPLACE if file does not exist itis created if it does existitis deleted and a new one created SCRATCH file is created and celeted when connection is closed UNKNOWN ACCESS char SEQUENTIAL default DIRECT FORM char FORMATTED default for sequential access UNFORMATTED default for direct access RECL positive integer record length for direct access obligatory maximum recordlength for sequertial access optional for formatted files length is number of characters in record for unformatted files length is system dependent but may be found with INQUIRE
271. for the initialization of objects in named COMMON blocks BLOCK DATA Rubbish COMMON NAME X Y X E DATA X Y X 1 2 3 248 END BLOCK DATA Rubbish Statements C through D CALL invokes a subroutine CALL PLONK CALL PLINK A B C CASE allows a selection of various ogtions SELECT CASE Ch CASE a z CASE low high PRINT lower case CASE A Z PRINT UPPER CASE CASE O EFAULT PRINT not a char END SELECT One of the bounds may be absert eg CASE 0 selects nom positive numbers The full definition is in Chapter 6 CHARACTER specifies character type The declaration has a number of forms e g CHARACTER 4 Word Word has length 4 CHARACTER LEN 8 Names 100 array of 100 names each of length 8 CHARACTER 4 N Line 80 N has length 4 Line has length 80 CHARACTER LEN 20 KIND 2 GreekWord CHARACTER INTENT IN Name assumed length dummy argument CHARACTER PARAMETER amp Message No such file named constant 249 CHARACTER isthe only one of the five irtminsic types to have two parameters length and kind CLOSE disconnects a file from a uni eg CLOSE 13 In general CLOSE
272. fore attempting to write the program The top down approach of flowcharts or structure plans means that the 43 overall structure of a program is clearly thought out before you have to worry about the details of syntax coding and this reduces the number of errors enormously Quadratic equation The equivalent structure plan for the solution of the quadratic equation flowcharted in Figure 4 3 is shown in Figure 4 5 Figure 4 4 Newton s method for square rooting Condition under which body of loop is executed fass of loop repeat 4 3 Structured Programming with Procedures Many examples later in this book will get rether involved More advanced programs like these should be structured by means of procedures subprograms which are dealt with in detail in Chapter 8 A procedure is a self cortained section of code which can communicate with the main part of the program in specific ways and which may be invoked or called by the main program The main program will then look very much lke a first level structure plan of the problem For example the quadratic equation problem may be structure planned at the first level as follows 1 Read the cata 2 Find and prirt the solution s 3 Stop Using a procedure actually a subroutine in this example this may be translated directly into a Fortran main program READ A B C CALL SOLVE _QUADRATIC A B C END
273. formula forthe number of years N to repay the loan is given by Fa Fpa tFn Write a new program to compute this formula Use the irtrinsic function LOG forthe logarithm How long will it take to pay off the loan of 50 000 at 800 a month if the interest remains at 15 Answer 10 2 years nearly twice as fast as when paying 658 a month Use your program to find out by trial anderrorthe smallest monthly payment that can be made to pay the loan off ever Hint recall that itis not possibleto findthe logarithm of a negative number so P must n be less than Fy z F a 2 15 The steady state current J flowing in a circuit that contains a resistance R 5 capacitance C 10 and inductance L 4 in series is given by P x 1 P x x where E 2 and Compute the value of Answer 0 0396 are the input voltage and angular f ency respectively 23 Chapter 3 Elementary Fortran II Chapter 3 Introduction 3 1 DO Loops e Square rocting with Newton e Money again e Differertidl interest rates 3 2 Deciding with IF THEN ELSE e The IF construct The IF statement 3 3 Characters e Character constarts e Charadter variables 3 4 Named Constants 3 5 Kind e Irtecer kinds e Real kinds e Character kinds 3 6 Complex Type 3 7 Introduction to Intrinsic Functions e Projetile motion e Some useful intrinsic functions e Irmtrin
274. gNo e g SHKWILOO1 as in Ex 12 7 LOGICAL Female TRUE for female FALSE for male INTEGER BirthDate e g 461121 REAL DIMENSION 20 Marks Marks END TYPE This is calledthe definition ofthe derived type First_Year A variable of thistype is declared as follows TYPE First Year Student and is called a structure Inthis case it has seven components Name Address etc Note that the severth componert is a real array for up to 20 marks The components are referenced with the component selector E g Student Birthdate 461121 The components may appear in any expression where a variable of the same type asthe component would be appropriate We can even ceclare an array of our cerived type TYPE First Year DIMENSION 100 Class Since an array section may end with a structure component the statement Class Female FALSE will then for example s amp the whole class gender to male To illustrete same more of the properties of structures le sdefine a simpler derived type TYPE Student_Type CHARACTER 20 NAMI REAL Mark END TYPE Gl Derived types have literal constarts e g Student _Type Smith JR 49 The order of components must follow their order inthe definition Although individual components may be assigned using the component selector as above allthe components may be assigned from the constant using a structure co
275. h warns you that no value has been assigned by the program to X However the line number given seems to refer to the last line inthe program Curiously however the following coding mins without emor under FTN 90 IMPLICIT NONI Gl REAL X The result is garbage 1 4209760E 14 withthe FTN 90 compiler on one occasion because of course X is undefined It seems as ifthe compilerthinks that because X appears on the left hand side of an assignment it must be defined There are many many more compiler errors you will probably have discovered a good number on your own by now With experience you will gradually become more adept a soctting your mistakes 7 2 Run time Errors If a program compiles successfully it will run Errors occurring at this stage are called runtime errors and are invariably fetal Le the program crashes An error message such as Floating point division by zero or Floating point arithmetic overflow is generated The latter is quite common E occurs for example when an attempt is made to compute a real expression which istoo large or when SQRT has a negative argument or when the argument of LOG is non positive Some compilers have irteractive debugging facilites where you can for example se through a program line by line until you findthe line wherethe rum rror occurs or where you can mark a line inthe code
276. h will court all the nomblank characters in atext 10 4 a Writea program which sets up a direct access file where each unformatted record contains a one dimensional integer array of size 10 say Write some test datatothe fi e and read it back to make sure it got there b Write a separete program which will add one extra record of the same length to the end of the file created in part a 10 5 Writea program which will read a positive integer of any size find its binary code and print the binary code on one line with no blanks bet ween the digits Hint after nding each binary digit store it in a differert element of an allocatable array 140 Chapter 11 Handling Characters Chapter 11 Introduction 11 1 Characters 11 2 Bar Charts and Frequency Distributions 11 3 Sorting Words 11 4 Graphs Without Graphics 11 5 Word Count and Extraction 11 6 General Information Character substrings Assumed character length Concatenation Embedded famat Character array constructors Character handling intrinsic functions Chapter 11 Summary Chapter 11 Exercises Chapter 11 Introduction We have seen some simple examples of the use of the intrinsic character type Armed with the further weapons of arrays and more advanced I O facilities we can now tackle more interesting problems involving characters or strings as they are
277. he system to reset the sed e GET rank one integer array size N has intent OUT and is set by the system tothe current valu of the seed Not more than one argument may be specified if none is specified the seed is set to a system dependent value See Chapter 14 for examples Real time clock CALL DATE AND TIME DATE TIME ZONE VALUES returns values are blank or HUGE 0 ifthe is no clock e DATE character as ccyymmdd century day e TIME character as hhmmss sss hours milliseconds e ZONI UTC S isthe sign Gl character as Shhmm difference between local and Co ordinated Universal Time e VALUES rank one integer array holdingthe year month day time difference in minutes with respect to UTC hour minutes seconds and milliseconds 212 CALL SYSTEM CLOCK COUNT COUNT RATE COUNT MAX returns e COUNT rteger holding current value of system clock e COUNT RATE irteger holding number of clock counts per second e COUNT MAX irteger holding maximum value COUNT may take Appendix D ASCII Character Codes The ASCII American Standard Code for Information Interchange collating sequence is as follows Ctl Dec Hex Char Coda oO Pyne WY we OO oT aa gt Nuh E 8 g a g o ol 3 g F fi ak gt 4 t B A B C D E F G H I J K L M N 0 P
278. his is often conveniert e enire arrays may be assigned an array which is currertly allocated may n be allocated again an array which is ceallocatedmust be currently allocated You may betemptedto writethis as a subroutine However dummy not ALLOCATABLE may not have the ALLOCATABLE attribute 9 5 Top of the Class The program in Chapter 5 to find the student withthe highest mark in a class assumes that there is only one top student Ifthere could be more than one name at thetop you can use an array to make a list of the top names IMPLICIT NONE INTEGER I student counter INTEGER TO value of IOSTAT INTEGER PARAMETER MAX 100 maximum class size INTEGER NumTop 1 must be at least 1 REAL Mark general mark REAL TopMark 0 can t be less than 0 CHARACTER 15 Name general name CHARACTER 15 DIMENSION MAX TopName top student OPEN 1 FILE MARKS DO READ 1 IOSTAT IO Name Mark IF IO lt 0 EXIT IF Mark gt TopMark THEN new top mark here TopMark Mark reset the top mark NumTop 1 only one at the top now TopName 1 Name here she is ELSE IF Mark TopMark THEN tie for top mark here NumTop NumTop 1 advance top counter 114 TopName NumTop Name add his name to the list END IF END DO DO I 1 NumTop PRINT TopName I TopMark END DO END To u
279. home or inthe bar Repeat a large number oftimes The proportion of walks that end up in either place should approach the limiting probabilities computed using the Markov model referredto in Exercise 15 2 Hint ifthe random number is less than 2 3 he moves toward the bar unless he is already at home or the bay in which case that random walk ends otherwise he moves toward home 15 4 Write a few lines of code to irterchange columns i and j of the matrix A 15 5 The following systen suggested by T S Wilson illustretes nicely the problem of ill conditioning mentioned in Exercise 7 3 10x 7y 8z 7w 32 7x 5y 6z 5w 23 8x 6y 10z 9w 33 7x 5y 9z 10w 31 Usethe Gauss reduction program inthis chapterto show thatthe solution isx y z w 1 Then change the right hand side constantsto 32 01 22 99 32 99 and 31 01 a change of about 1 in 3000 and findthe new solution Finally change the right hand side constartsto 32 1 22 9 32 9 and 31 1 and observe what effect this has on the solution 223 Chapter 16 Introduction to Numerica0l Methods Chapter 16 Introduction 16 1 Equations e Newton s method e Complex rocts e The Bisection method e Passing procedures as arguments 16 2 Integration e The Trapezoidal Rule e Irtrinsic functions as arqumerts e Simpson s Rule
280. ical Motion under Gravity 2 7 Programming Style 2 8 Numeric Expressions e Integer divisim e Mixed mode expressions 2 9 Numeric Assignment e Examples 2 10 Simple Input and Output e Input e Example e Reading data from text files e Output e Sending output tothe prirter Chapter 2 Summary Chapter 2 Exercises Chapter 2 Introduction Inthis chapter and the next one we wil look in detail at how to write Fortran programs to solve simple problens There are two essertial e requirements for successfully mastering this art The exact rules for coding instructions must be learnt A logical plan for salving the problem must be developed These two chapters are devoted mainly to th first requirement learning some basic coding rules Once you have masteredthese we can go on to more substantial problems All Fortran 90 statements introduced in this and subsequent chapters and some which are not are summarized in Appendix B 2 1 Compound Interest Again In Chapter 1 you ran the program MONEY to compute compound irterest P ROGRAM MONEY Calculates balanc REAL BALANC INTER after interest compounded EST RATE F py F 17 F 1000 BALANCE 0 09 EST RATE INTER BALANCE PRINT F RATE BALANCE BALANCE INTEREST New balance BALANCI F
281. ided by another integer quantity the result is also of irteger type so it is truncated towards zero i e the fractional part is lost E g L073 evaluates to 3 19 4 evaluates to 4 Ap 5 evaluates to 0 which could cause an unwanted division by zero 833 evaluates to 2 3 10 3 evaluates to 10 10 3 3 evaluates to 9 Mixed mode expressions Fortran 90 allows operands in an expression to be of differert type The general rule is that the weaker or simpler type is converted or coerced into the stronger type Since integer type is the simples this means that operations involving real and integer operands will be done in real 16 arithmetic This applies to each operation separately not necessarily to the expression as a whole So for example 0 30 evaluates to 3 33333 5 evaluates to 0 8 2 evaluates to 0 2b SS NO BR However ncte that Sef Bf S00 evaluates to 0 333333 because 3 2 is evaluated first giving irteger 1 2 9 Numeric Assignment The purpose ofthe numeric assignment isto computethe value of a numeric expression and assign it to a variable ts general form is variable expr The equal sign does not have the same meaning asthe equalsignin mathematics and should be read as becomes So the assignmert X A B should be read as the contents of X becomes the contents of A plus the conterts of B Inthis
282. iesthe intrinsic ordering ofthe available character set The Fortran 90 standard requires only that A lt B lt C lt Y lt Z OSL 23 B59 e blank lt AandZ lt 0 ablank lt O and9 lt A Tf lowercase letters are available there are the further requirements that e a lt b lt cu lt y lt z e 6blank lt aandz lt 0 wblank lt Oand9 lt a Note that the standard does not insist on how the lowercase characters are to be ordered relative to uppercase There are two irtrinsic functions that relate a characterto its position in the collating sequence or more simply its code ICHAR A returns an irteger code for its character argument e g 65 say inthis case CHAR 90 returnsthe character coded by its irteger argument eg 4 say Furthermore the standard requires that access be providedtothe ASCII American Standard Code for Information Interchange collating sequence in which Z lt a see Appendix D There are two further irtrinsic functions which specifically relate a character to its ASCII code IACHAR and ACHAR However some computers make use of the EBCDIC collating sequence Extended Binary Coded Decimal Interchange Code pronounced ebsadik In EBCDIC unfortunately the lowercase characters come before the uppercase ones so z lt A This has implications for word sorting since we normally require that bOnApArTe lt NaPoLeOn whatever
283. if k 0 labelsthe firstterm x the second term labelled by k 1 can be obtained from the first term by multiplying it by _x 2k 2k 1 Work out the first few terms by hand as a check The program is as follows 71 PROGRAM Taylor Computes sine x from Taylor series INTEGER PARAMETER Pi 3 14159278 INTEGER K t term counter INTEGER MaxTerms 10 max number of terms REAL Err le 6 max error allowed REAL Sine sum of series REAL Term general term in series REAL X angle in radians PRINT Angle in degrees READ X X X Pi 180 convert to radians Term first term in series Sine Term DO WHILE ABS Term gt Err and K lt MaxTerms Term Term X X 2 K 2 K 1 K K 1 Sine Sine Term END DO IF ABS Term gt Err THEN why did DO end PRINT Series did not converge ELSE PRINT After K terms Taylor series gives Sine PRINT Fortran 90 intrinsic function SIN X END IF END The DO WHILE may be replaced by DO IF ABS Term lt Err or K gt MaxTerms EXIT END DO Note how the logical condi im must DO WHILE orEXIT atthe enough in which case k will F top of suill ke Note also that there are two condi be negated it is now the condition to
284. ified on a particular computer by using a kind parameter This is discussedin Charter 3 Positive whole numbers may also be represented in binary octal ase 8 or hexadecimal form e g binary B 1011 ectadl 0 0767 hexadecimal Z 12EF 12 Lower case may be used Quotation marks may be used instead of apostrophes as delimiters These forms are restrictedto use withthe DATA statement and in internal and external files as digit strings without the leading letters and the delimiters Real literal constants These are used to dencte values of real irtrinsictype and take two forms The first form isthe obvious one and is called positional form or fixed point and consists of a string of digits with a decimal poirt Ir may be signed or unsigned Examples 0 09 37 37 0 0 68297135 There may be no digitstothe left of the decimal poirt or no digitstothe right of the decimal point but a decimal point by itself is n allowed The second fom is called exponential form or floating point Tt basically consists of either an integer signed or unsigned or a fixed poirt real signed or unsigned followed in both cases by the letter E followed by an integer signed or unsigned The number following the E is the exponent and indicates the power of 10 by which the number preceding the E must be multiplied E g 2 0E2
285. ights and reset timer Lights I 1 Cars advance red timer display traffic queue change lights and reset timer 5 G KKKKKKKKKK 6 G KKK 7 R KKKKKK 8 R KKKKKK 9 R KKKKKKKK 10 R KKKKKKKKK 45 R KKKKKKKKKKKKKKKKKKKKKKKKK 46 R KKKKKKKKKKKKKKKKKKKKKKKKKKK 47 G KKKKKKKKKKKKKKKKKKKKK 48 G KKKKKKKKKKKKKK From this particular run it seems that a traffic jam is building up although more and longer runs are needed to see ifthis is really so In that case one can experiment with different periods for red and green lights in orderto get an acceptable traffic pattern before settingthe real lightstothat cycle try it This is the great value of this sort of simulation Of course we can get closer to reality by considering two way traffic and allowing carsto turn in both directions and occasionally to break down but this program gives the basic ideas Chapter 14 Summary e A simulation is a computer program written to mimic a real life situation which is apparently based on chance e The pseudo random number generator RANDOM NUMBER returns a uniformly distributed random number inthe range 0 1 and isthe basis of the sim ions discussed in this charter e RANDOM SEED enables the random number generatorto be seeded by the user The seed may be obtained from SYSTEM CLOCK which returns the system clock time
286. ike The following piece of code will set up a linked list by reading numbers from the keyboard until a zero is entered 179 DO WHILE Num 0 READ Num IF Num 0 THEN ALLOCATE Current new node Current Value Num Current Next gt L point it to previous node L gt Current update end of list END IF END DO Tf for example the values 1 2 3 are entered in that arcer the lis looks as shown in Figure 13 1 Having set up the lis the next thing isto traverse it and prirt allthe values This is psychologically satisfying because it s sometimes hardto behevethe listis reallytherein memory since none of the nodes have names This is where itisimportartto know wherethe end of the list is L pointsto it So we start by making our general node Current an alias of L Current gt L Then we prirt the value intha node and make Current an alias ofthe next node which is pointed Q toby Current Next R2 RINT Current Value o urrent gt Current Next Q How do we detect the beginning of the list Remember that the poirter in the first node at the beginning of the list is null this can betested for sothe abovetwo statements can be enclosed ina DO WHILE loop DO WHILE ASSOCIATED Current PRINT Current Value Current gt Current Next now make Current alias of next node END DO
287. ilable for storage so that for example there might be two kinds of integer short and long There is a full discussion of kind in Chapter 3 In addition to the intrinsic data types you may define your own derived data types each with their own set of values and operations This is discussed in Chapter 12 Integer and real intrinsic types are discussed below Character and complex intrinsic types are discussed in Chapter 3 the remaining intrinsic type logical is dealt with in Chapter 5 2 4 Literal Constants 11 Literal constants often simply called constants are the tokens used to denote the values of a particular type i e the actual characters that may be used Before we consider constants in detail we need to look briefly at how information is represented in a computer Bits n bytes The basic unit of information in a computer is a bit something which has only two possible states usually described as on and off The binary digits 0 and 1 can therefore be used to represent these two states mathematically hence the term digital computer The word bit in a contraction of binary digit Numbers in a computer s memory must therefore be represented in binary code where each bit in a sequence stands for a successively higher power of 2 The decimal numbers 0 to 15 for example are coded in binary as follows Decimal Binary Hexadecimal Decimal Binary Hexadecimal 0 0000 Q 8 1000 amp 1 0001 1 9 1001 9 2 0010 2 10 101
288. ile everything as more and more stubs are filled in E g PROGRAM BigOne IMPLICIT NON Gl 102 CA CA 1 FIRST LAST CONTAINS SUB P END RINT SUB Hej RINT el Z o ii H ROUTIN L SUBRO ROUTIN L SUBRO ROGRAM BigOne S F a Eai First here UTINE FIRST AST UTINE Last here TE may n domuch a this tags but amp least it compiles 8 10 Recursion Many mathematical functions and more general procedures may be defined recursively i e in terms of simpler cases of themselves For example the factorial functim may be d as n n n 1 given that 1 is ned as 1 finiti To implement this q Fortran 90 thisis not possible header the function may cal ition a RESULT clause must be added to the functio header in order to use a However ifthe RECURSIV fined recursively on as a function itis necessary forthe functionto call itself Normally in E keyword is pre ed to the function 1 itself Ifthe callis direct Lethe function name occurs in the body of the function definiti different local defined recursively IMPLICIT NONE INTEGER I I 10 PRINT I Factorial 1
289. ime 193 707 721 prime and 2 147 483 647 prime Tf such things irterest you the largest prime number at the 99 796 839 ie 1 thas time of writing is 227 832 digits and takes up about 7 pages of newsprirk Obvi ously this program cannot test such a large number since it s greater than the largest integer which can be represented by a Fortran irtrinsictype Ways of testing such huge numbers for primality are describedin D E Knuth The Art of Computer Programming Volume 2 Seminumerical Algorithms Addison Wesley 1981 Knuth The DO WHILE form of the DO construct would be very conveniert to use here Step 4 of the structure plan needs to be changed to 4 While R 0 ana N lt VP repeat andthe DO must ke rephrased as 70 DO WHILE Rem 0 AND N lt SQRT REAL P N N4 2 Rem MOD P N END DO Note that the condition is the logical negation of the condition to exit as given originally Reading an unknown amount of data The next program uses DO WHILE witha special feature of the general READ statement to read an unknown amount of deta from a file DATA andto findtheir mean REAL A SUM INTEGER N 0 INTEGER IO 0 OPEN 1 FILE DATA SUM 0 DO WHILE IO 0 READ 1 IOSTAT IO A IF IO 0 THEN SUM SUM A N N 1 PRINT A END IF E
290. imes If there is no data value between successive separetors the corresponding input item is left E g the code CHARACTER 20 Name Ace 370 Be S37 C 3 D 3 RI CIND P EFAD Name A B RINT A 4F6 2 Name A B C D under the FTN 90 compile with input fortran 90 245 2 7 gives the output fortran 90 2 20 2 20 7 00 7 00 2 2 is a garbage undefined valus NAMELIST undefined under the FTN90 compiler a Ithough the standard requires that it is left unchanged Thisis a curious facility which can be usedto name a group of items for1 O purposes It allows you to omit input data for some items in the group The group of items is named in a NAM statement MYOUT in the example below The group name may either be speci fied with t specifier in READ or WRITE or it may replace the format specifi r An inpu ELIST he NML t record must be prefaced by amp followed by the group name Data values may be omitted in which casethe record 138 must end witha slash and do n have to be in the order specified in the NAMELIST statement Eems not specified in the input record are left unchanged E g INTEGER DIMENSION 4 A 7 NAMELIST MYOUT A X Y X 1 Y 1 READ MYOUT WRITE NML MYOUT Input amp MYOUT A 1 2 2 1 Y 3 Outpu
291. in Fortran in over 20 years and brings it into line with most modern structured programming languages This book is one of a handful on Fortran 90 and one of even fewer in which every program unless otherwise clearly stated has been tested on a working compiler the FTN90 compiler for PCs If you are a newcomer to Fortran you should read the book in the conventional way from the beginning However if you are a Fortran 77 user you may like to dip immediately into later chapters to see some of the new features of the language Probably the two most important advances are the new array facilities Chapters 9 and 15 and the impressively enlarged collection of intrinsic procedures Appendix C including the so called elemental functions which operate on all or selected elements of array arguments You may now define your own types or structures Chapter 12 and even construct linked lists with them using pointers Chapter 13 Modules Chapter 8 may be independently compiled and may contain type definitions and variable declarations as well as procedures The use of interface blocks Chapter 8 makes it possible to overload specific procedure names with generic names and also to overload operators Conditional loops are possible now with DO WHILE Chapter 6 and there is a new CASE statement Chapter 6 However you should probably first have a look at Sections 2 2 2 5 program layout variable declarations etc and Section 3 5 kind to
292. ine arc cosine AIMAG Z imaginary part AINT A KIND largest whole real number nct exceeding its argument e g AINT 3 9 returns 3 0 ANINT A KIND nearest whole realnumber eg ANINT 3 0 returns 4 0 ASIN X inverse sire arc cosine ATAN X inverse tangent arc tangert inthe range 1 2 to 7 2 ATAN2 Y X invers tangert arc tangent as principal value of the argument of the complex number X Y inthe range T to T CEILING A smallest irteger not less than A CMPLX X Y KIND converts Xor X Y to complex type CONJG Z conjugate of camplex Z COS X cosine COSH X hyperbolic cosine DIM X Y max X Y 0 EXP X exponential function FLOOR A largest irteger not exceeding its argument eg FLOOR 3 9 returns 4 INT A KIND converts to irteger type truncating towards zero LOG X LOG natural logarithm for complex X result isthe principal value LOG10 X common base 10 logarithm MAX A1 A2 A3 maximum of arguments MIN A1 A2 A3 minimum of arguments MOD A P remainder of A modulo P ie A INT A P P E g MOD 2 2 2 0 returns 0 2 MODULO A P A modulo P for A and P both real or bothinteger i e A FLOOR A P P inthe real case and A FLOOR A P P inthe integer case where represents mathematical division E g MODULO 10 3 retums 2 MODULO 2 2 2 0 r
293. ing program usesthe Newton quotiertto estimate f x for f s 7 a x 2 for smaller and smaller values of h the exact answer is 4 REAL NO X H INTEGER I N X 2 H 1 PRINT How many READ N PRINT A10 A12 H NQ DO I 1 N NQ F X H F X H PRINT E10 4 F12 8 H NQ H H 10 END DO CONTAINS FUNCTION F X REAL F X F X 2 END FUNCTION F END Output H NQ 0 1000E 01 5 00000000 0 1000E00 4 09999371 0 1000E 01 4 01000977 0 1000E 02 4 00066423 0 1000E 03 3 99589586 0 1000E 04 4 00543261 0 1000E 05 3 81469774 3 The results show that the best h for this particular problem is about 10 But for h much smaller than this the estimate becomes tctally unreliable Using double precision real kind improves the accuracy Change REAL to REAL 2 H NQ 0 1000E 04 4 00001000 0 1000E 05 4 00000100 0 1000E 06 4 00000009 0 1000E 07 3 99999998 0 1000E 08 4 00000033 0 1000E 09 4 00000033 0 1000E 10 4 00000033 0 1000E 11 4 00035560 8 The best value is now about 10 3 Generally the best h for a given problem can only be found by trial and error Finding it constitutes a major problem of numerical analysis This problem does not arise with numerical irtegration because numbers are added to find the area not subtracted 232 16 4 First order Differential Equations The most interesting situations in real life that w
294. intemal This also makes it easier for you to run and develop the program Consequently the fi the end In a real appli declarations such as the is ope type defini ned once atthe beginning of the program and closed only at ion the subroutines would probably be in a module with some global ion the file name etc In that case each subroutine which handles the file should open and close it The program outline is PROGRAM Stude IMPLICIT NONE KFE Records INTEGER PARAMET TYPE StudentRecord ER NameLen 20 CHARACTER NameLen Name INTEGER Mark END TYPE StudentRecord TYPE StudentRecord Student INTEGER EOF RecLen RecNo LOGICAL IsThere CHARACTER NameLen FileName CHARACTER Ans CHARACTER 7 FileStatus CHARACTER PARAMETER NameChars amp abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPORSTUVWXYZ INQUIRE IOLENGTH RecLen Student WRITE File name ADVANCE NO READ FileName INQUIRE FILE FileName EXIST IsThere IF IsThere THEN WRITE File already exists Erase and recreate Y N amp ADVANCE NO READ Ans IF Ans Y THEN FileStatus REPLACE erase and start again B iS BE FileStatus OLD
295. ion is performed on corresponding positions along a dimension nct on corresponding subscris 207 As another example suppose A is a 3 x 3 matrix In orderto find itsinverse by Gauss reduction a 3 x 6 augmented matrix B is formed with A occupying its first three columns and the identity matrix occupying its lat three columns E g if A is given by 2 l 1 1 1 1 3 p vl B willke 2 l 1 1 0 0 1 1 1 0 1 O 3 1 1 0 0 1 If Idn represents the identity matrix B can be set up intwo lines B 123 15 3 A 4 6 Idn Some more intrinsic functions Eis generally more efficiert to use the intrinsic functions to handle arrays rether than to operate directly on their elements E g add up the elements of an anay with SUM rather than in a DO loop MAXVAL A and MINVAL A return the maximum and minimum elements of the array A respectively MERGE A B MASK is an elemental function meaning it operates on each element of its arguments returning a corresponding element t returns A if the logical array MASK istrue and B otherwise E g ifthe arguments represent matrices C MERGE A B A gt B returns a matrix C such that is the larger of ana Di RESHAPE SOURCE SHAPE reshapesthe array SOURCE irtothe shape given by the elements of the array SHAPE which must be constart i e the firs element of SHAPE givesthe extert size of the first dimension of
296. ions or subroutines A function returns a value which has atype A function is invoked by referencing its name No value is atached tothe name of a subroutine A subroutine is invoked witha CALL statemert Dummy arguments are used in a subprogram s declaretion actual arguments in its invocation The compiler provides explicit irterfaces to intrinsic internal and module subprograms An EXTERNAL statement in the calling program is sufficient to link to an external subprogram in normal circumstances An interface block may always be used to provice an explicit irterface to an external subprogram there are situations when one must be used Figure 8 1 A module may contain declarations specification statements and subprograms Entities in a module specified with the PRIVATE attribute may only be accessed within the module Entities are public by default The scope of a name or labelisthe set of lines where it may be used unambiguously Scoping rules for labels and names are differert Actual arguments may be passedto subprograms by reference or by value An argument passed by reference may be changed on return Constarts or expressions are passed by value Parentheses around a variable name make it an expression Dummy arguments may be specified withthe INTENT attribute IN may not be changed inthe subprogram OUT
297. is again the function to be irtegreted so there is an interface block for Fung E is assumed thet the user will choose h in such a way that the number of steps n will be an irteger a check forthis could be buit in ANES As an example let s irtegrate f x A between the limits 0 and 4 We needto write an external function again FUNCTION F X REAL F REAL INTENT IN X F X 3 END FUNCTION F A main program could look like this PROGRAM TestTrap USE NumUtils IMPLICIT NON DE GI REAL A B H INTERFACE FUNCTION F X REAL F X ND FUNCTION F INTERFACE o Fl EN F Ea T U RINT Enter A B H EAD A B H 7 U m ND PROGRAM TestTrap the estimate gets more accurate RINT Integral F8 4 Trap A B H F With h 0 01 the estimate is 64 0004 the exact irtegralis 64 You will findthat as h gets smaller This example assumes that J x is a continuous function which may be evaluated at any x In practice the function could be defined at discrete points supplied as results of an experiment For example the speed of an object v t might be measured every so many seconds and one might want to estimate the distance travelled as the area under the speed time graph Inthis case Trap would have to be changed by replacing F Fung A Fung A
298. is mentioned laterwhen we look at non deterministic 63 6 4 Nested DOs Loan Repayments Tf a regular fixed payment P is made n times a yearto repay a loan of amount A over a period of k years where the nominal annual irterest rete isr Pis given by rA l r n ni l r n 1 The next program uses nested DOs to print a table of the repayments on a loan of 1000 over 15 20 or 25 years at irterest ratesthat vary from 10 to 20 perannum P is directly proportionalto A in Equation 6 1 Therefore the repayments on a loan of any amount may be found fram the table genereted by the program by simple proportion The WRITE statements used to make the output look neater are explained in Chapter 10 You can probably figure out how they work IMPLICIT NONE INTEGER I counter INTEGER N 12 number of payments per year INTEGER K repayment period yrs INTEGER TRIPS iteration count REAL A 1000 principal REAL P payment REAL R interest rate REAL RO R1 RINC lowest highest interest and increment READ RO R1 RINC TRIPS INT R1 RO RINC RINC 2 1 R RO PRINT Rate 15 yrs 20 yrs 25 yrs PRINT DO I 1 TRIPS WRITE F5 2 S ADVANCE NO 100 R DO K 15 25 5 P R N A 1 R N N K 1 R N N K WRITE
299. is neatly transformed if we spot that x is related to X n l as follows xX ax Nn There are no numerical problems now The following program computes Xn for a 10 and increasing values of n and prirts it for every terth value ofn REAL X 1 REAL A 10 INTEGER N DO N 1 100 X A xX N IF MOD N 10 0 PRINT N X END DO Complex transfer function The response output of a linear system which may bethought of as a black box is characterized in electrical engineering by its transfer function An input signal with a given angular frequency radians s is applied at one end of the box The output from the other end isthen given by the input multiplied by the absolute value of the transfer function with its phase shifted by the phase angle of the transfer function Suppose a servomechanism is characterized by the transfer function Tio K 04io l 0 2i ia 1 2 5io 1 143ia 1 0 02ia where 7 is the unit imaginary number v 1 j in electrical engineering and K is an amplification factor T isa complex number If its real and imaginary parts vetumed by REAL and AIMAG 52 2 are a and b respectivelythen its absolute valueis V b andits phase angle is given by arctan b a Ifthe ATAN2 intrinsic function is used the angle retumed will be inthe range m to m so that the correct qu
300. ive even integers 2 4 200 Answer 10100 37 3 6 Ten students in a class write atest The marks are out of 10 All the marks are entered in an external fileMARKS Write a program which will read allten marks from the file and find and display the average mark Try it on the following marks each on a separate lire in the file Dr BP OE TA aSe Be 5 Te e 24 Answer 5 9 3 7 The pass mark forthe test inthe previous problem is 5 out of 10 Change your program so it uses an IF THEN to find out how many students passed the test 3 8 Write aprogram which generates some random numbers R with CALL RANDOM NUMBER R and courts how many of them are greaterthan 0 5 and how many are lessthan 0 5 Try increasing the number of random numbers genereted What do you expect 3 9 What are the values of X and A bcth real after the following program section has been executed x Px PK Px DX H P ll x Px PK Px POR O tee tte test HHHHHHHH 3 10 Rewrite the program in the previous exercise more economically by using a DO loop 3 11 Work out by hand the output of the following program PROGRAM Mystery REAL S X INTEGER N K 4 S 0 DO K 1 N KS S S 1 X X faster than X 2 END DO PRINT 10 Sqrt 6 S 10 FORMAT F10 6 END Tf you run this program for larger and larger values of N you will findthat the output approaches a we
301. ix is a two dimensional array which may be used ina wide variety of representations For example a distance array representing the lengths of direct connections in a network is a matrix We will deal mainly with square matrices inthis chapter i e matrices havingthe same number of rows as columns although in principle a matrix can have any number of rows or columns A matrix with only one column is also called a vector A matrixis usually dencted by a bold capital letter e g A Each entry orelement ofthe matrixis dencted by the small letter ofthe same name followed by two subscritts the first indicatingthe row of the element andthe second indicatingthe column So a general element of the matrix A is called Y meaning it may be found in row i and column j If A hasthree rows and columns 3 times 3 for short it will look like this in general Ay Ay ag Ay Ay 3 a a a F f p 3132 33 special matrix which we willcome across later isthe identity matrix This has ones on the main diagonal and zeros everywhere else E g the 3 times 3 identity matrix is 1 0 0 0 1 0 00 1 Various mathematical operations are defined on matrices Addition and subtraction are obvious and may be done withthe irtrinsic operetors in Fortran 90 So the matrix addition A B C translates directly irto Aven B t C where the arrays must clea
302. l N ND FUNCTION Factorial m Inthe case of a recursive function the form is eg RECURSIVE FUNCTION Factorial N RESULT Fact T The type can be specified inthe FUNCTION statement as in INTEGER FUNCTION Factorial N Statements G through H GOTO not recommended transfers control unconditionally to a labelled statment GOTO 70 There are two other forms of GOTO assigned GOTO see ASSIGN and computed GOTO The computed GOTO looks like this GOTO 20 50 10 40 N Control passesto the statement withthe Nth label inthe list e g tothe statement labelled 10 if N evaluates to 3 253 Statements through K IF transfers control conditionally There are three distinct forms e The logical IF statement is used when a single statement is to be executed under a certain condition IF A 0 X B 2 A out e The IF construct is used when blocks of statements are to be cuted under certain conditions IF Num gt 0 THEN PRINT positive ELSE IF Num 0 THEN PRINT zero ELSE PRINT negative END IF e The arithmetic IF isa dangerous statement since its use tends to be coupled with the occurrence of numerous GOTO statements A Balfour and D H Marwick Programming in Standard FORTRAN 77 Heinemann London 1979 p 291 tis obsolescent and not re
303. l needto be maintained inthis way Ikistherefore extremely important to developthe art of writing programs which are well laid out with all the logic clearly described This is known as programming style and shouldbe manifest in most of the programs inthis book occasional lapses are in arder to save space Guidelines for good style are laid out inthe Epilogue The program in the previous section has been written with this in mind e Ther is acomment amp the beginning describing what the program does e All the variables have been declared and described on separate lines in alphabetical order You may like to include initialization with the declaration and descriction eg 15 REAL T 6 time e Blanks have been used on either side of the equal signs andthe operetors e g and after commas e Blank lines have been used to separate distinct parts of the program You may like to develop your own style the poirt is that you must pay attention to readability 2 8 Numeric Expressions The program Vertical in Section 2 6 makes use of the following code Ut PSG a REC This is an example of a numeric expression a formula combining constarts variables and functions like square root using numeric intrinsic operators Tt specifies a rule for computing a value Since it only computes a single value itis a scalar numericexpression There are five
304. lan and program forthe problem are 1 Start 2 Initialize balance year rate Interest 3 Write headings 4 Repeat Update balance according to interest rate Write year irterest balance until balance exceeds twice original balance 5 Stop IMPLICIT NONE INTEGER Year REAL Interest New Old Rate PRINT Original balance READ Old Rate 0 1 New Old keep a copy of the original balance Year 0 68 PRINT Year Interest Balance PRINT DO Interest Rate New New New Interest Year Year 1 PRINT Year Interest New IF New gt 2 Old EXIT END DO The condition New gt 2 Old is checked each time before ancther iteration Repetition occurs only if the condition is true The DO block must be executed at least once since you must invest your money fora least a year for anythingto happen Consequertly the EXIT must be atthe end of the DO The output looks like this for an opening balance of 1000 Year Interest Balance 1 1 0000000E 02 1 1000000E 03 2 1 1000000E 02 1 2100000E 03 i 1 7715611E 02 1 9487172E 03 8 1 9487172E 02 2 1435889E 03 Notethat when the last iteration has been completed the conditionto EXIT istrue forthe first time since the new balance 2143 59 is morethan 2000 Note alsothat a deterministic DO cannot be used here because we don t know how many iter
305. lasses IF Final gt 75 THEN PRINT Name CRM ExmAvg Final 1 49 Firsts Firsts 1 ELSE IF Final gt 70 THEN PRINT Name CRM ExmAvg Final 2 UpSeconds UpSeconds 1 ELSE IF Final gt 60 THEN PRINT Name CRM ExmAvg Final 2 LowSeconds LowSeconds 1 ELSE IF Final gt 50 THEN PRINT Name CRM ExmAvg Final 3 Thirds Thirds 1 B iS B PRINT Name CRM ExmAvg Final F Fails Fails 1 END IF This saves time because Fortran stops checking as soon as it finds a true logical expression So if Final gt 75 istrue it won t botherto check further The onus rests on you therefore to code th construct correctly so that only one of the logical expressions is true Note also how inde The IF construct in general A more general form of the IF construct is IF logical expri THEN blockl ELSE IF logical expr2 THEN block2 ELSE IF logical expr3 THEN block3 B S E blockE END IF Tf logical expr is true the amp emerts in block are executed and co statemer t after statemer ts in block2 are executed foll END IF If logical expr is false logical expr2 is eval lowed by the next statement after ion makes the st
306. lay a message followed by the conterts of BALANCI ion Put the number 1000 irto memory 1 i F py ER F an Gl OY Oe AR Qo Stop During execution these translated statements are carried out in order from the top down At execution the memory locations used will have the following values fter BALANCE 1090 INTEREST 90 RATE 0 09 Note that the original contents of BALANCE is lost The PROGRAM statement in the first line introduces the program It is optional and may be followed by an optional name The second Line starting with an exclamation mark isa comment for the benefit of the reader and has no effect on the compilation Variables in a program can be of different type the REAL statement declarestheirtype inthis example The firstthree non hlank lines ofthis program are non executable i e no action is carried out by them they have no counterpart in the translated form of the program above Try the following exercises Run the program Change the first executable statement to read BALANCE 2000 and make sure that you understand what happens when you run the program again 3 Leave out the line BALANCE BALANCE F INTEREST and rerun Can you explain what happens Gl 4 Try to rewrite the program so that
307. le dencted by a character variable CHARACTER 4 BUFFER READ BUFFER 14 YI m AR REAL declares objects with ral type thasa number of forms eg REAL A colons optional REAL B 10 initialization colons obligatory REAL X 0 10 array The following attributes may be specified in a type declaration ALLOCATABLE DIMENSION EXTERNAL INTENT INTRINSIC OPTIONAL PARAMETER POINTER PRIVATE PUBLIC SAVE TARGET Most attributes may be specified with any of the intrinsic types CHARACTER COMPLEX INTEGER LOGICAL and REAL or a cerived type Attributes may specified in separate statements eg 260 A double colon must appear whenever there is an initialization expression or an attribute is specified If a constart is named withthe PARAMETER attribute there must be an initialization expression Array bounds may be specified after a name instead of with the DIMENSION attribute E g REAL PARAMETER g 9 8 named constant INTEGER PARAMETER Max 100 REAL DIMENSION Max X INTEGER N Max I I 1 Max array constructor INTEGER ALLOCATABLE Network REAL DIMEN
308. lias of some ob7ect or whether it is null t can also determine whether a poirter is an alias of a particular target e An ordinary variable is all ocated static storage compile time e A dynamic variable is allocated dynamic storage amp run time e A dynamic variable is created with the ALLOCATE statement and referenced with a pointer e Dynamic memory is released with DEALLOCATE e A dynamic array can have eitherthe ALLOCATABLE or POINTER attribute Its rank must be specified but its bounds executed for i must be left undefined until an ALLOCATE statement has been e Arrays of pointers may not be declared directly in Fortran 90 However a derivedtype may b defined with apoirter componert and an array of such a type can be declared e Implementation details of abstract cata types may be hidden in modules Chapter 13 Exercises 13 1 Write some lines of code which set up two pointers P1 and P2 as aliases of the integers I and J respectively 184 Now write some additional code which effectively makes P1 an alias of J and P2 an alias of I without referring to I and J explicitly 13 2 Set up an array of structure variables with a single pointer componert and arrange for itto poirt to an array of irteger values suitably initialized Referring onlytothe array
309. ll known lmit 3 12 The electricity accounts of residerts in a very small town are calculaed as follows endexercises e if 500 units or less are used the cost is 2 certs 100 certs 1 per unit e if morethan 500 but not morethan 1000 units are used the cost is 10 forthe first 500 units and then 5 cents for every unit in excess of 500 38 e if morethan 1000 units are used the cost is 35 forthe first 1000 units plus 10 cents for every unit in excess of 1000 e in addition a basic service fee of 5 is charged no matter how much electricity is used Write a program which readsthe names and consumptions of the following users from an external file and displays the name consumption and tctal charge for each user Ahmed A B 200 Baker C D 500 Essop S A 700 Jansen GM 1000 Smith Q G 1500 Answers 9 15 25 40 90 3 13 month the balance is 50 50 and aftertwo months itis 101 51 Suppose you deposit 50 per month ina bank accourt every month fora year Every month after the deposit has been made interest at the rate of 1 is added to the balance E g after one Write a program to compute and prirt the balance each month fora year Arrange the output to look something like this MONTH MONTH END BALANCE 1 50 50 2 101 521 3 153 02 12 640 47 3 14 If you invest 1000 for one year at an interest rate of 12 the retumis 1120 atthe en
310. lues Ifthis were nct so it would be necessary to sort them first 124 125 Chapter 10 Advanced Input and Output Chapter 10 Introduction 10 1 Rabbit Breeding the Fibonacci Way 10 2 The PRINT Statement 10 3 Formatting Features e Edit igtors e Data edit descrittors e The character string edit desarictor e Control edit descrittors e Repeat counts e Carriage control 10 4 Formatted READ 10 5 Formatted WRITE 10 6 Internal Files 10 7 External Files e File positioning Sequential files e Unformatted 10 e Diet access files e The INQUIRE statement 10 8 Non advancing I O 10 9 Miscellaneous e List directed 10 e NAMELIST Chapter 10 Summary Chapter 10 Exercises Chapter 10 Introduction So far we have concentreted on writing programs to salve various problems without paying too much attention to how the output looks In this chapter we will see how to use FORMAT specifications to produce neater output We will also look at cata transfer involving files 126 10 1 Rabbit Breeding the Fibonacci Way To make the exercise more interesting we will write a program to model a rabbit population using the following assumptions 1 We start with me new born male female pair 2 A new born pair produce a male female pair aftertwo months 3 Male female pairs of age two months and alder produce a
311. ly be used as a last resort TE would be betterto use atext editor to change the original names The other way in which access to a module may be a statement E g the statement aru F B US YourMod ONLY Xy Y Gl ffected is by the ONLY clause in the USI allows accessto only the entities X and Y of the module The items following the colon may also be renames PUBLIC and PRIVATE attributes Each module accessed must appear in a sparte USE statement As we have seen all entities in a module are accessible by default to any program unit that uses the module However access may be restricted by specii its declaration REAL PRIVATE X fying a variable withthe PRIVATE attribute in Alternatively a variable or subprogram may be speci P RIVATE X SWOP T accessible inside the module however he PUBLIC attribute the default may be similarly specifi ed with this attribute in a separate statement his means that the entities X and SWOP are ng available outside the module They are still d T T he statement PUBLIC or PRIVATE statements PRIVATE UBLIC SWOP A7 ntities inthe modul make all with no entity list confirms or resets the default So the PRIVATE by default excect for SWOP 97 8 6 Scope The scope of a label or name is the s
312. m rether like aBubble Sort INTEGER DIMENSION 52 Hand I I 0 51 DO Card 1 52 CALL RANDOM _NUMBER R Num INT 52 R 1 Temp Hand Num Hand Num Hand Card Hand Card Temp END DO Notethat Num is now inthe range 1 52 since it represerts the position of a card rather than the card itself The only other change requiredisthat Hand must t have 52 elements With a few amendments a deal of all four hands can now be prirted you can alsothink about sorting each hand before it is printed rether like players sort their cards after a deal You couldtest which of the two shuff time RANDOM NUMBER is called A nu of the average number of calls 14 7 Traffic Flow fling methods is m ore efficient by incrementing a counter each mber of sample runs wouldthen be neededto get an estimat A major application of simulation is in modelling the traffic flow in large cities in orderto try out different traffic light patterns on the computer before inflictingthem on the real traffic this has been done on a large scale in Leeds inthe United Kingdom for example In this example we look ata very small part of the
313. male female pair every month Tf we representthe number of male female pairs after n months by the variable Fy some scratching around with apencil and paper soon reveals that F takes the following values Month n1 2 3 4 5 6 7 8 Population F 1 1 2 3 5 8 13 The sequence F is calledthe Fibonacci sequence We wantto write a program that computes the tctal populatio for up to say 12 months Note that this model does not allow for deaths this possibility is discussed in Chapter 15 t can be shown that each term inthe sequence isthe sum of the previous two Le We therefore need to have three variables inthe program Fn Fn_1 and Fn_2 which needto be updated each month assuming that we are not going to use an array An interesting feature of the Fibonacci sequence is that We will also compute this ratio to verify that it has a limit in fact the limit isthe same whatever the firs two values in the sequence are The program below uses FORMAT statementsto control the layout of the output to give you an idea of what can be done The details are then discussed Rabbit breeding the Fibonacci way IMPLICIT NONE INTEGER Month REAL Fn Fn_1 Fn 2 Format specifications 10 FORMAT Month T12 Population T27 Ratio amp RO PLZ A LOC ys oT 29 SCs yf 20 FORMAT 13 T12 F7 1 T27 F6 4 Now the executables Em sb c Fn 2 1 PRINT
314. me represent the same thing Perhaps it should be noted that Fortran programmers have a long tradition of writing programs in uppercase only This goes back to the days which I remember well when card punch machines had to be used these can represent only uppercase letters A mixture of upper and lowercase is howevey much easier to read it contains more information than pure uppercase So it might be betterto use NoOfStudents than NOOFSTUDENTS It is also generally better to use meaningful names which are n foo long however such as NoOfStudents instead of simply N There are no reserved words in Fortran you may therefore use the name END for a memory ion although this is certainly not recom mended The following table shows scme valid and invalid names Valid names Invalid names why X X Y R2D2 SHADOW FAX 13 Pay Day 2A ENDOFTHEMONTH OBI WAN A variable is a memory location whose value may be changed during execution of a program A variable s name is constructed according to the above rules A variable has a type which determines the type of constant it may hold tis given atype ina bpe declaration eg INTEGER X REAL INTEREST CHARACTER LETTER REAL A 1 Note that a variable may be initialized in its declaration In this case a double colon must be used The value of a variabl
315. ment PUT This is a rank one irteger array which is usedto reset the seed Seed forrandom number generation Ik may be supplied directly by the user with a READ statement or it may be generated itself from the system clock as inthis example As long as the system clock keeps on ticking you will g different results every time you run this code 14 2 Spinning Coins When a fair unbiased coin is spun the probability of getting heads ortailsin 0 5 50 Since a value returned by RANDOM NUMBER is equally likely to anywhere in the interval 0 1 we can represert heads say with a value less than 0 5 ctherwise it will be tails Suppose an experiment calls fora cointo be spun 50 times andthe results recorded In real life you are likelyto wantto repeat such an experiment a number of times thisis where computer simulation 187 times INTEGER Count I REAL DIMENSION 50 R CHARACTER 1 DIMENSION 50 COINS INTEGER DIMENSION 1 Seed CALL SYSTEM CLOCK Count Seed Count DO I 1 5 CALL RANDOM SEED PUT Seed PRINT Seed CALL RANDOM NUMBER R WHERE R lt 0 5 COINS H ELSEWHERE COINS T END WHERE PRINT 50A1 COINS CALL RANDOM SEED GET Seed END DO END Output ishandy The following program simul
316. ment of the main program Subprograms look almost like a main program except for their headers and END statements Internal subprograms may not cortain other subprograms and so may not themselves have a CONTAINS statement The general syntax of an irtemal function is 88 FUNCTION Name argument list declaration statements executable statements ND FUNCTION Name ty The statement FUNCTION Name argument list is called the function statement or header or declaration Note that if the main program has an IMPLICIT NONE statement and sound programming style insists that it should have one the function name and arguments must be declared with atype Although this may be done inthe main program it is recommended that you declare the function name and arguments in the function body itself Since a value is associated withthe function name this value must be assignedtothe function name in the functim body Note that when the function name appears on the left hand side of an assignment statement its arguments must be omitted e g YNew X SIN A Y COS A inthe function YNew above The function issaidto return this valuetothe calling or host program A function value may also be returned by means of a RESULT clause see below An internal subprogram automatically has access to all its host s entities Variables declared in the host program are therefore global inthe sense that the
317. mentary and are ignored by the compiler An entire lire may be a comment A blank line is also interpreted as comment Comments should be used liberally to improve readability Continuation lines Tf a statement istoo longto fit on a line it will be continued on the next line if the last non blank character in it is an ampersand amp A AI4O amp LO Cak 2 ee lt 3 Continuation is normally to the first character in the next non comment line However ifthe first normtblank character of the continuation line is amp continuation istothe first character afterthe amp In this way atoken may be split overtwo lines although this is not recommended since it makes the code less easy to read An amp atthe end of a comment lire will n continue the comment sincethe amp is construed as part of the comment 2 3 Data Types The concept of a data type is fundamental in Fortran 90 A data type consists of a set of data values e g the whole numbers a means of denoting those values e g 2 0 999 and a set of operations e g arithmetic that are allowed on them The Fortran 90 standard requires five intrinsic i e built in data types which are divided into two classes The numeric types are integer real and complex The non numeric types are character and logical Associated with each data type are various kinds This is a basically the number of bits ava
318. mes J is hashed to the integer K The item s position J in Names is placed in Index K A positive value should never be returned to Place by Find necessary until either an unused position Index K 100 a match is not being sought from Place A positive value means a duplicate item in Names INTEGER J K INTEGER DIMENSION Index CHARACTER DIMENSION Names K Find Index Names Names J lt IF K gt 0 THEN position occupied we should never get her S Place is used to set up the hashed list Index from the list of l l l l PRINT Names J already known at hash position K PRINT New simple position J will be inaccessible ELSE K K Index K J END IF ND SUBROUTINE Place El 0 Fl N enlarged arrayNames Dealing with additional items is simple Justaddthem on atthe end of the disk file and rehash th 169 Chapter 12 Summary The TYPE statement defines a derived data type A derivedtype may have components of differert types including arrays and her structures A variable of a cerived type is called a structure Structure components are referenced withthe componert selector Arrays of structures may be ceclared A structure may be initialized with a structure constructor either in an initialization expression or in an
319. mportant difference is that our pointer L of Section 13 2 which marked the end of the LIST This isto enable a user of the module to declare a variable of thistype to name his lst without needing to know precisely how the type is defi ned All occurences of L inthe coding in Section 13 2 must therefore be replaced by L End The PRIVATE speci fications mean that the type NODE is inaccessible outside the module and that the user will not have access to the irternal structure of type LIST W S Brainerd C H Goldberg and J C Adams Brainerd Goldberg and Adams Programmers Guide to Fortran 90 McGraw Hill 1990 suggestthat the subroutine SetUp be written as a function to return a null poirterto head the lis FUNCTION SetUp TYPE IST SetUp NULLIFY SetUp END FUNCTION SetUp pe End which is invoked in the accessing program as follows L Setup 182 where Lis oftype LIST This however isnot allowed underthe FTN90 compiler it will n return a null porter To use this implementation of a lig all that is needed is amain program like the following PROGRAM TestList USE ModLink linked list implementation IMPLICIT NONE TYPE LIST INTEGER Num 1 CALL SetUp L DO WHILE Num READ Num je IF Num 0 THEN CALL Insert L Num END IF END
320. mpute and display the population every ten years from 1790 to 2000 Use the intrinsic function EXP X to compute the exponen tial e 39 Use your program to find out ifthe population ever reaches a steady state i e whether it stops changing 3 17 A frut packaging company wants a program that reads the number of apples that can be packed into one box BOX andthe tctal number of applesto be packed APPLES and prirts out the number of boxes needed FULL andthe number of apples left over LEFT a Write a tutue plan forthe problem gt Write the Fortran program 3 18 There are 39 37 inches ina metre 12 inches ina foot and three fet ina yard Write a program to read a length in metres which may have a decimal part and convert itto yards feet and inches Check 3 51 metres converts to 3 yds 2 ff 6 19 in 3 19 Write some Fortran statements which will a findthe length C of the hypctenuse of a right angletriangleinterms ofthelengths A and B of the cther two sides b findthe length C of a sice of a triangle given the lengths A and B of the cthertwo sides and the size in degrees of the included angle 9 using the cosine mule C A B 2ABcos 0 3 20 Translate the following formulae into Fortran expressions a 0g x x a o e t sin 4t cos 3t 4 arctan 1 2 a Sec x cot y 1 cot x a 3 21 A sphere of mass m impinge
321. n necessarily an array may be created as follows REAL POINTER Pl ALLOCATE P1 This makes the poirter P1 an alias of an area of memory ableto store a real variable Note that no value is assigned at this stage However since P1 is an alias it may now be used as any other real variable can be e g Pl 17 PRINT Pl The memory poirtedto by Pl can ke released by the statement DEALLOCATE P1 This returns P1 tothe undefined state it had a the beginning of the program Both ALLOCATE and DEALLOCATE have an optional specifier STAT e g ALLOCATE P1 STAT AlloStat 174 The irteger variable AlloStat will zero only if memory was successfully allocated or deallocated When an array is specified with the ALLOCATABLE or POINTER attribute its bounds must be undefined REAL DIMENSION POINTER X INTEGER DIMENSION ALLOCATABL mi D Danger The ability to create dynamic memory brings greater versatility and f om to program ming but also requires greater responsibility In particular there aretwo potential sources of disaster which need to be studiously avoided The first isthe dangling pointer Consider the fallowing REAL POINTER Pl P2 ALLOCATE P1 Pl 13 P2 gt Pl P1 and P2 beth reference the same dynamic variable If now
322. n Figure 12 2 Take the first element Ann and perform some operation onthe characters in the name to produce a positive integer e g add up the ASCII codes of the characters This process is called hashing itis done by a hash function andthe resultart integer is called the hashed index let s call it K Now set up a second array Index and store in Index K Ann s position in Names i e 1 Suppose K has the value 43 Then Index 43 will have the value 1 as in Figure 12 2 The name Ann is inserted for clarity Now take some other item in Names e g Tony and hash it withthe same hash function whatever it is Suppose the hashed index is 1 Thentake Tony s positimin Names whichis 4 and storeitin Index 1 asin the figure Figure 12 2 Hashing Names Index Ann 1 4 Tony Jack 2 100 empty Tor Tony 42 100 empty David 43 1 Ann DEUN Obviously K is going to have to be reduced modulo the length of the array Index e g if Index has indices fi 1 to 53 say and K turns out to be 4575 tmust be reduced by the operation K MOD K 53 1 to pt i inthe range 1 53 We continue this process for all the items in Names You might have thought of an objection by now Itis most unlikely that the hash function will produce a unique value of K for each item inthe lig So when setting up the hashed list in Index a partic
323. n a function could be defined in a single lirs e g E X K RE 3 K en 8 90 ETURN This form is supported by Fortran 90 but is not recommended since it does not follow many of the general rules for subprograms Internal subroutines Subroutines ave very similarto functions The differences are e No value is associated withthe name of a subroutine hence it must nd be declared e A subroutine is invoked witha CALL statement e The keyword SUBROUTINE is used inthe definition andthe END statement e A subroutine need n have any arguments in which case the name is written without parentheses e g CALL PLONK A function without arguments must have enpty parentheses eg Fung The following program prirts a line with the subroutine PrettyLine which has two dummy arguments Num is the number of characters to be printed Symbol isthe ASCII code of the characters to be jorirted IMPLICIT NON Gl CALL PrettyLine 5 2 CONTAINS SUBROUTINE PrettyLine Num Symbol I CHARACTER 80 Line D oO I 1 Num Line I I ACHAR END DO PRINT Line END SUBROUTINE END NTEGER I Num Symbol Symbol Character substrings such as Line I I are discussed in Chapter 11 The next example shows how dummy argumerts may be usedtotake information back tothe calling program in this case their values are exchanged IMPLIC
324. n integer array and reads it back INTEGER DIMENSION 10 A I I 1 10 OPEN 1 FILE TEST FORM UNFORMATTED WRITE 1 A REWIND 1 A 0 just to be sure READ 1 A PRINT A CLOSE 1 END Note that to read the file it must be rewound since it is sequential by default Each READ and WRITE transfers exactly one record The file created in this example therefore has one record containing an aray of 10 irtegers When output isto a sequential file a record of sufficient length is created On input the number of items inthe input list must not exceed the number of values in the record Direct access files Inthe case of direct or random access files a particular record may be read and or rewritten unlike the case with sequertial access files where records may not in general be replaced Records may also be added at the end of a direct access file without rewritingthe whole file Direct access files are unformatted by default and alltheirrecords must be the same length This record length must be specified with the RECL specifierinthe OPEN statement Record length is generally the number of bytes occupied by the item written to the file but may be system dependent The INQUIRE statement may be used to find the record length see below The following example reads a list of names from the keyboard writes them to a direct access file reads them back and finally replaces the third
325. n matrix REAL DIMENSION 6 Se xX state vector INTEGER I T P 0 construct probability matrix DO I 3 6 P L 2 1 23 3 P I 2 I 1 1 3 END DO P 1 1 1 P 6 6 1 X 7 0 Ly 0 07 0 20 7 initialize state vector PRINT A4 6A9 wy Time Home HM Ww WA now Bar PRINT DO T 1 50 KAS PP ars OK PRINT 14 6F9 4 T X END DO END PROGRAM Drunk Output Time Home 2 3 4 5 Bar 1 0 3333 0 0000 0 6666 0 0000 0 0000 0 0000 216 2 0 3333 0 2222 0 0000 0 4444 0 0000 0 0000 3 0 4074 0 0000 0 2962 0 0000 0 2962 0 0000 4 0 4074 0 0987 0 0000 0 2962 0 0000 0 1975 5 0 4403 0 0000 0 1646 0 0000 0 1975 0 1975 6 0 4403 0 0548 0 0000 0 1755 0 0000 0 3292 7 0 4586 0 0000 0 0951 0 0000 0 1170 0 3292 8 0 4586 0 0317 0 0000 0 1024 0 0000 0 4072 9 0 4691 0 0000 0 0552 0 0000 0 0682 0 4072 10 0 4691 0 0184 0 0000 0 0596 0 0000 0 4527 40 0 4838 0 0000 0 0000 0 0000 0 0000 0 5161 50 0 4838 0 0000 0 0000 0 0000 0 0000 0 5161 By runningthe program for long enough we soon findthe limiting probabilities he ends up at home about 48 of thetime and atthe bar about 52 ofthetime Perhaps thisis a little surprising from the transition probabilities we might have expected him to get tothe bar rether more easily t just goes to show that you should never trust your irtuttion when it comes to statistics Note that the Markov chain approach is not a simula
326. n steps of 0 1 say Run the program for differert values of n e g 1 3 6 etc 6 9 Ifanamount of money A is invested for k years ata nominal annual irterest rate r expressed as a decimal fraction the value V of the investment after k years is given by V A 1 r n where n isthe number of compounding periods per year Write a program to compute V as n gets larger and largey i e as the compounding periods become more and more f ert like monthly daily hourly etc Take A 1000 r 4 and k 10 years You should observe that your output gradually approaches a limit Hint use a DO loop which doubles n each time tatting withn 1 k Also compute the value of the formula Ae forthe same values of A r and k use the intrinsic function EXP and compare this value with the values of V computed above What do you conclude 6 10 Write a program to computethe sum ofthe series 1 2 3 such thatthe sum isas large as possible without exceeding 100 The program should write at how many terms are used inthe sum 6 11 One of the programs in Section 6 5 shows that an amount of 1000 will double in about seven years with an irterest rate of 10 Usingthe same irterest rate run the program with initial balances of 500 2000 and 10 000 say to see how longthey alltaketo double The results may surprise you 6 12 Write a program to implement the struc
327. n this irterval see Figure 16 1 Inthis example KEST and Xr will do since f aol and f 2 ee Inthe Bisection method we estimatethe roc by Xu where XM isthe midpoint of the 5 Xr X oe BOR SD ie Xpa G Xp Z2 ded Then if I Xm has the same sign as f as drawn inthe figurs the roc clearly lies bet ween Xm and Xr We mustthen redefinethe left hand end of the irtervalas havingthe value of Xu Le we le the new value of x be Xu Otherwise if fu and f have different signs we let the new value of Xr be Xu since the roct must lie bet ween Ar and Xm in that case Having redefined Mi or Xr yas the case may be we bised the new interval again according to Equation 16 1 and repeat the process until the distance bet ween Xr and Xr is as small as we please 226 Figure 16 1 The Bisection method The neat thing about this method is that we can calculate before starting how many bisections are needed to obtain a certain accuracy given initial values of XL and R Suppose we stat with x a Xg b After the firt bisection the worst possible error E in M is and E la b 2 ginc we are estimatingthe rog as being at the midpoint ofthe irterval a b The worst that can happen is that the roct is actually at ae or a in which case the error is E s i 2 Boisa E la b 2 Carrying on likethis af
328. n under EN9 3 as 2 170E 03 or 2 170 003 The ES scientific edit descriptor isthe same as the EN descriptor except that the mantissa is less than 10 Complex values may be controlled by pairs of F E EN or ES edit descrigtors The real and imaginary parts may have different descriptors which may be separeted by character string and control edit descrictors Logical values are controlled by the L edit descriptor inthe form Lw On output T or F will appear in the right most position of the field w On input optional blanks are optionally followed by a decimal poirt followed by T or F upper or lowercase optionally followed by additional letters This curious arrangement is smply to allow the amp rings TRUE or FALSE to be input Character values are controlled by the A edit descritor in one of two fomms A or Aw Inthe form A the wicth ofthe I O fields is determined by the length of the character variable or expression in the I O list E g if NAME is declared 129 CHARACTER NAME 7 then 7 characters are output and 7 characters are input Inthe second form Aw the w left most characters are prirted on output If necessary the output field is blank filled from the left The rules for input under the second form are a little strange Suppose len i
329. n using up to now eg PRINT The answer is X e a character expression or constant which evaluates to a format specification in parentheses e g PRINT The answer is F6 2 X The quantities in list may be constants expressions variables or implied DO lists of the form do list variable expr1 expr2 expr3 where items indo list may themselves be implied DO lists READ can be used inthe same way as PRINT except that the quantities in the list must he variables 10 3 Formatting Features In this section we discuss the details of format control for input and output Edit descriptors Edit descriptors such as F7 1 inthe program above specify exactly how a quantity should appear on output or in preparation for input More technically they specify how a value represerted irternally by the computer should be converted into a readable characterstring on an output device or file ar converted from a character string on an input device or file There are three categories of edit descrictors deta character string and control Data edit descriptors In the descriptions below the symbols w m d and e all represert integer constants while b represents a blank 128 field wicth is too narrow it is filled with Tn all cases involving numeric output if the specified asterisks Integer values are
330. nderstand what the program does run through it by hand make a lis of the variables and enter their values withthe following data Botha 58 Essop 72 Jones 72 Murray 2 Rogers 90 Tutu 90 Then run it onthe computer as a check Note that at the end the name Murray will still be in the array in TopName 3 but his name will not be prirted because NumTop has been reset to 2 You could try to rewrite this program with TopName as an allocatable array to save memory space 9 6 Sorting a List The Bubble Sort One of the standard applications of arrays is sorting a list of numbers into le amp us say ascending order The basic idea istha the unsorted list isread into an array The numbers arethen ordered by a process which essertially passes through the lis many times swopping consecutive elements that are inthe wrong order until allthe elements are inthe right order Such a process is called a Bubble Sort because the smaller numbers riseto the top of the list like bubbles of airin water In fact in the version shown below the largest number will sink to the bottom of the list afterthe first pass which really makes it a Lead Ball sort There are many other methods of sorting which may be found in most textbooks on computer science one of them the Quick Sort is given in the next section These are generally more efficiert thanthe Bubble Sort but its advantage isthatitis by far the easiest method to program
331. nditionally to the labelled statement E g GO TO 99 X 67 8 99 Y 1l The statement X 67 8 is never executed perhaps causing a shipto sink an airplaneto crash or a shuttle launch to abort Novices may ask why GO TO is ever needed Its use goes back to the bad old days when older versions of Fortran lackedthe block IF construct andhadto make do withthe simple IF statement Consider the following clear segment of code L1 and L2 aretwo defined logical variables IF L1 THEN I l J 2 ELSE IF L2 THEN I 2 J 3 B iSE T 3 ro ei 4 END IF Inthe absence of the IF construct this must be coded as the following tangle of spaghetti IF NOT L1 GOTO 10 I l J 2 GOTO 30 10 IF NOT L2 GOTO 20 I 2 J 3 GOTO 30 20 L 3 J 4 55 30 CONTINUI Dummy statement does nothing Need we say more except that GOTO should never be used it will n be foundin any examples in this book TE ismentioned here purely for historical and pedagogical reasons Chapter 5 Summary e The IF construc allows forthe conditional execution of blocks of statements e The IF statement allows forthe conditional execution of a single statement e The IF constuict may have any number of ELSE IF clauses but no more than one ELSE clause e The IF contua may be named e IF constructsmay be
332. nds output to an output unit In general WRITE UNIT u FMT fmt spec list list The specifiers are the same as for READ except that there is doviously no END specifier E g WRITE 2 10F5 3 X I I 1 N WRITE 1 List directed output on unit 1 WRITE 3 REC 76 A direct access write to record 76 Non advancing WRITE is useful for writing prompts Gl WRITE A ADVANCE NO amp Enter a number not list directed There are no EOR or SIZE specifiers for non advancing ouput 264 Appendix C Intrinsic Procedures Intrinsic Procedures C 1 Elemental Numeric Functions C 2 Elemental Character handling Functions C 3 Non elemental Character handling Functions C 4 Functions Relating to Numeric Representation e Numeric inquiry functions e Elemental functions to manipulate reals C 5 Bit Manipulation Functions e Inquiry funtion Tj lemental functions wlemental subroutine Tj C 6 Vector and Matrix Multiplication Functions C 7 Array Reduction Functions e Optional argument DIM e Optional argument MASK C 8 Array Inquiry Functions C 9 Array Construction and Manipulation Functions C 10 Inquiry Functions for Any Type C 11 Elemental Logical Function C 12 Functions Relating to Kind C 13 Transfer Function C 14 Non elemental Intrinsic Subroutines e Random numbers e R
333. ne or more qualifiers e g Class 3 6 Class 5 BirthDate Consequertly in Fortran 90 the term array now means any object that is not scalar including an array section or an array valued component of a structure The term variable now means any named object that is not specifiedto be a constart and any part of such an object including array elements array sections structure components and sulostrings 12 2 A Database Student Records Inthis section we combine the elegance of Fortran 90 derived types with direct access filesto build a program to illustrate the basic principles of setting up disolaying and updating a database 158 Suppose we want to s amp up a da relatingto each student For simp tabase of student records by record we mean the information licity let s record each studert s name including initials and one irteger mark in practicethis is more lkelyto be an array of marks The obvious vehicle forthisis a derived type similar to that defined in the previous section TYPE StudentRecord INTEGER END TYP CHARACTER NameLen E StudentRecord Name Mark We need a collection of subroutines to read and write variables of this type to and from a direct access file The program template follows Details of the subroutines are filledin below For ease of presentation the subroutines are
334. ng and solvable problems begins to unfold One such problem is preserted in this section The wildebeest gnu population in the Kruger National Park South Africa declined from about 14 000 in 1969 to 6 700 in 1975 giving rise to considerable concern see Table 6 1 Mathematical modellingtechniques were appliedtothis problem as describedin A M Starfieldand A L Bleloch Building Models for Conservation and Wildlife Management MacMillan 1986 The population in year k may be divided into four biologically distinct age groups Cr the number of new born calves Ye the number of yearlings ty the number of two year olds W the number of adults alder than two years We can think of the population as a vector with four componerts each measured annually in January when the females calve The essence of the problem is to predict the next year s vector given an initial population at some time At this stage we turntothe game rangers who tell us that yearlings do nct produce young this is the prerogative of the two year olds and adults We thus have the equation modelling the dynamics of calves Cka Wy ta e where a and a are the birthwzates number of expected offspring per individual per year for adults andt wo year olds respectively Itturns out that the best way to model yearling population dynamics is simply Vir DC where b is
335. ng back END DO ND SUBROUTIN Chapter 16 16 1 m GI zZ Ba H K w 5 n a The real mts are 1 856 and 697 the complex rocts are 0 079141 7801 0 589 3 096 6 285 octs get claserto multiples of n O 1445 1 303 6 Real rocts amp 1 768 and 2 241 285 16 2 Successive bisections are 1 5 1 25 1 375 1 4375 and 1 1 414214 so the last bisection is within the required error 16 3 22 exact answer is 21 3333 rt 16 4 After 30 years the exact answer is 2117 1000e ye 16 5 The differential equations to be salved are dS dt r S dY dt r S 1r Y 16 6 ROGRAM IMPALA NTEGER I N B H R T X RINT Enter R B A X 0 H P I R P READ R B A X H N 24 T 2 DO I N IF MOD I 1 INT 1 H SPACING H ll I 40625 The exact answer is The exact solution after 8 hours is S 6 450 x 10 and Y 2 312 x 10 f H SPACING H 1 trip count THEN output every month starting with initial value PRINT 2F8 2 T X END IF p Ts X H R B XK SIN A T ND ND DO fi El X 16 7 With 10 irtervals n 5 the luminous efficiency is 14 512725 With 20 intervals it is 14 512667 These results justify the use of 10 irtervalsin any further computations involving this problem This isa standard way of testingthe accuracy of a numerical method halvethe ste
336. ngth specified by the length parameter Pad with blanks ifnecessary CHARACTER 6 DIMENSION 3 Primary RED BLUE amp YELLOW Character handling intrinsic functions Fortran 90 has a number of new intrinsic functions relating to strings of characters which greatly enhance its string handling capabilities putting it on a par with languages such as Pascaland C A brief descriction of what they can do is given here details ave in Appendix C ADJUSTL adjusts left to retum a string with leading blanks removed and inserted as trailing blanks ADJUSTR adjusts right 148 INDEX returns the starting position of the first ar last occurrence of a substring in a string EN returns the length of a string EN TRIM returns the length of a sting without its trailing blanks REPEAT retums a string formed from multiple concatenations of a string e g REPEAT X 3 returns XXX SCAN returns the position of the left ar rightmost character of one string which appears in another TRIM returns a String with all its trailing blanks removed VERIFY retums zero if each character in one string appears in another string orthe position of the left ar rightmost character of one string which does net appear in andher string E g CHARACTER PARAMETER
337. nstructor either in an initialization oc in an ordinary assignment TYPE Student Type Studentl Student _Type Bloggs 50 A variable of a derived type may appear in an I O lig as long as there is an appropriate format specification for each componert 153 PRINT A20 F6 0 Studentl A variable of a cerived type may be assigned to ancther variable of the same type Student2 Studentl All the components of Student2 are replaced by the corresponding components of Studentl Defined assignments overloading We have just seen that the intrinsic assignment operator is automatically available for derived types We can however redefine the assignment operatar by overloading it This feature of Fortran 90 as well as general operator overloading which is present in object oriented programming languages like C will astonish Fortran 77ers t may take a little getting used to Suppose as a simple illustration we want to redefine the assignment for Student_ Type intwo ways Firs we would like a short hand way of assigning a name directly without using the component selector or a constructary e g Student Smith JR on the understanding that no value is assigned to the mark Second we would like to extract the name directly from the variable again without using the component selector e g StuName
338. nt array of rank greater than one can be constructed from an array constructor using the RESHAPE intrinsic function E g RESHAPE SOURCE 1 2 3 4 5 6 SHAPE 2 3 forms the 2 times 3 matrix 13 5 2 4 6 Array sections A subarray called a section may be referenced by specifying a range of subscris e g X I J rank one array of size J I 1 YoGLge bJ rank one array of size J e g the Ith row of a matrix with J columns X 2 5 8 9 rank one array of size 4 2 hnical lemer An array section istecl although its individua reference the second is naturally X I ly an array and may appear in statements where an array is appropriate lements may not be referenced directly So we can t writ X J 2 to t ofthe section X I J Rather write X I 1 sincethe first element One or bcth of the bounds in a section may be omitted anda tri ctherthan 1 may be used 3 sks Be the whole of row J elements 1 4 7 of row J A section subscrict may even be a one dimensional array of irteger type E g the coding REAL DIMENSION 10 R Po AEP TS 2 20 2 AA INTEGER DIMENSION 5 B 5 4 3 2 1 PRINT A B produces the output 10 00 8 00 6 00 4 00 2 00 A subscript of this nature is called a vector subscript The elements of a vector subscript may be in any order E g ACU 3 5 1 2 isa section of A wi
339. nt at the end of a DO loop DO 10 I 1 100 10 CONTINUI Gl This is not recommended use DO with END DO instead 250 CYCLE not recommended transfers controltothe END DO statement ofthe current DO construct The next iteration ifthere is one is initiated If you want toleave out part of a loop sometimes you should rewrite it DATA initializes objets during compiletime This is particularly useful for arrays REAL A 10 X 5 B C D DATA A 10 1 X I I 2 4 1 2 3 DATA B C D J 4 5 6 Note the optional comma separating a value lst from a following object lst DEALLOCATE releases dynamic storage m DEALLOCATE Pl P2 In general DEALLOCATE list STAT st See ALLOCATE forthe analogous meaning of STAT DIMENSION declares an array Itis n recommended as a separate statement See REAL for its use as an attribute DO repeats a block of statements a specified number of times e g DO I 1 100 I incremented by 1 by default END DO and DO K 10 1 2 K decremented by 2 END DO DO may also be used with a conditional EXIT e g DO IF ABS F X lt 1E 6 EXIT END DO 251 DO parameters should be irtegers The use of real parameters is obsolescent and not recommended The full definition of DO is in Chapter 7
340. nternal file and character substrings to also be written 144 draw a sine graph over one period This technique can only draw graphs with no morethan one plating symbol per line of output A more general graphing procedure is discussed in Chapter 15 HARACTER 70 Line AL PARAMETER Pi 3 1415927 AL dx X TEGER N Trips FORMAT A70 dx Pi 20 Trips INT 2 Pi dx dx 2 1 Xo S 0 PRINT X T37 SIN X l heading PRINT DO I 1 Trips WRITE Line F4 2 X Line is an internal file N NINT 25 1 SIN X 15 Line 40 40 Line N N Figure 11 1 Graph on the text screen X SIN X 00 X JES 31 i sAN K 62 x 78 X 94 10 26 41 257 ES 88 04 x 20 36 51 s07 x 83 98 14 WNHNHNNNNNFFRRFRRRFPODTWVOVCVCCO PRINT 10 Line X X dx END DO END Part of the output is shown in Figure 11 1 11 5 Word Count and Extraction When the authorship of a piece of prose is uncertain it sometimes helps to calculate the average number of words per sertence andthe standard deviation of this statistic A first year class of mine once foundthat with samples of about 700 lines G K Chesterton is easily distinguishable from Lord Macaulay the former having a significartly shorter mean sertence length with a larger standard
341. numeric irtrinsic operators shown in Table 2 1 Typing blanks on either si of operators will make expressions more readable These operators are called intrinsic because they are builtin We will see later how to define new operators and how to overload an irtrinsic operator Le give it a different meaning An operator with two operands asin A B is called a binary or dyadic operator When an operator appears with only one operand as in Z itis called unary or monadic The order in which operations in an expression are carried out is determined by the precedence of the operators according to the table above except that parertheses always have the highest precedence Since multiplication has a higher precedence than addition this means for example that 1 2 3isevaluatedas7 while 1 2 34isevaluatedas 9 Notealsothat 3 2 evaluates to 9 nat 9 When operators withthe same precedence occur inthe same expression they are with one exception always evaluated from lefttoright sol 2 Aisevaluatedas 1 2 Aandnal 2 A The exception tothe precedence rules is that in an expression of the form A B the right hand operation B C is evaluated first Integer division This causes so much heartache amongst unsuspecting beginners that it deserves a section of its own When an integer quantity constart variable or expression is div
342. o length and see how much the solution changes 286
343. of bacteria divides or dies according to the following assumptions 1 during a fixed time interval called a generation a single bacterium divides into two identical replicas with probability p 2 ift does net divide during that irterval it dies Le caases tobe shuffles off this mortal coil 3 the offspring called daughters will divide or die during the next generation independently of the past hitoy thee may well be no offspring in which case the colony becomes extinct Start with a single individual and write a program which simulates a number of generations Take p 0 75 The number of generations which you can simulate will depend on your computer system Carry out a large number e g 100 of such simulations The probability of ultimate extinction p E may be estimated as the proportion of simulations that end in extinction You can also estimate the 195 mean size of the nth generation from a large number of simulations Compare your estimate withth theoretical mean of 2p Statistical theory shows that the expected value of the extinction probability p F isthe smaller of 1 lt and 1 p p So for p 0 75 p E is expected to be 1 3 But for pss D E is expectedto be 1 which means that extinction is certain a rather unexpected result You can use your
344. of f x REAL DF X DF 3 KX 2 1 END FUNCTION DF PROGRAM Newton m 2 UO Fl Note that there are two conditions that will stoothe DO loop either convergence orthe completion of 20 iterations Ctherwise the program could run indefinitely Rotation of co ordinate axes Functions are particularly useful when arithmetic expressions which can become long and cumbersome need to be evaluated repeatedly A good example is the rotation of a Cartesian co ordinate systen If such a system is rotated cournter clockwisethrough an angle of a radians the new co ordinates x y of a point referred to the rctated axes are given by x x cos a y sin a y sina y cosa where x y are its co ordinates before rotation of the axes The following functions could be usedto define the new co ordinates FUNCTION Xnew X Y A REAL XNew X Y A Xnew X COS A Y SIN A ND FUNCTION Xnew eal FUNCTION YNew X Y A REAL YNew X Y A YNew X SIN A Y COS A END FUNCTION Ynew Internal functions Since functions and subroutines are very similar common features are described by referring to them collectively as subprograms Most of the following rules apply alsoto external subprograms except where otherwise stated All internal subprograms are placed between a CONTAINS statement andthe END state
345. of h then t nh If we define Yn as vio v t h then Ym We can therefore replace Equation 16 7 with the iterative scheme Vaa Y th g v 233 Vv 9 T Since we are given the initial condition finding the Euler approxi mat a G Eis very easy to program Euler s method We can al h and comparing the results with the exact solution jon Vn to v 4 in general Equation 16 8 provides a numerical scheme for lsotest its accuracy by trying different values of The following program uses Euler s method as implemented in Equation 16 8 to estimate v forthe first 24 seconds of the skydiver smotion It also computes the exact salution for comparison PROGRAM Para IMPLICIT NONE REAL PARAMETER g 9 8 REAL K H T TO Tend V VO X INTEGER I N PRINT Enter K H TO V TO Tend READ K H TO VO Tend X Tend TO H N INT X SPACING X 1 trip count T TO V VO PRINT 3A10 Time Euler Exact DO I 1 N PRINT 3F10 2 T V Vexact T VO G K V V H g K V V T T H END DO CONTAINS FUNCTION Vexact T V0 G K REAL Vexact REAL INTENT IN g K T VO REAL A C A SQRT g K C A V0 A VO Vexact A C EXP 2 A K T C EXP 2 A K T END FUNCTION Vexact END PROGRAM Para Taking h 2 and
346. of the jety atthe quay end and poirts him towardthe ship Suppose at every step he has a 60 chance of lurching towardthe ship but a 20 chance of lurching tothe left or right he manages always to be facing the ship If he reaches the ship end of the jetty he is hauled aboard by waiting mates The problem is to simulate his progress along the jety and to estimate his chances of getting tothe ship without falling intothe sea To do this correctly we must simulate one random walk along the jetty find out whether or not he reaches the ship and then repeat this simulation 100 times say The proportion of simulations that end withthe sailor safely in the ship willbe an estimate of his chances of making ittothe ship Fora given walk we assume that if he has not either reached the ship or fallen intothe sea aftey say 10000 steps he dies of thirst on the jAty To represent the jety we set up co ordinates so that the x axis runs along the middle of the jety withthe origin at the quay end x and y are measured in steps The sailorstarts his walk at the origin each time The structure plan program and output from two successive runs are as follows Ig Initialize variables 2 Repeat 100 simulated walks down the jety Start at the quay end of the jety While sil on
347. often called 141 11 1 Characters To recap a character constant is a string of characters enclosed in delimiters which are either apostrophes or quotes The delimiters are not part of the string Character variables may be declared in the following ways CHARACTER ALPHA length of 1 CHARACTER 15 Name length of 15 CHARACTER Word 5 length of 5 Assignment is done as follows Name Bonaparte N 11 2 Bar Charts and Frequency Distributions The first example utilizes an array and the A edit descrixtor for pirting characters Suppose we wart to analyse the results of atest written by a class of studerts We would like to know how many students obtained percentage marks in the range 0 9 10 19 90 99 Each of these ranges is called a decile numbered from zero for convenience We also need to cater forthe bright sparks who get 100 the eleventh decile Suppose the numbers of students who get marks in these ranges are as follows 10 12 9 31 26 49 26 246 1 Le 12 obtained marks inthe range 2029 Weneedan array F 0 10 say with 11 elements where each element stares the number of students with marks inthat particularrange e g F 2 should have the value 12 The following program prirts a bar chart of the frequency distribution F where each asterisk represerts one student in that range INTEGER DIMENSI
348. ogical SUM and are replaced by ANY and AND C 7 Array Reduction Functions The following seven functims all have array arguments MASK is a logical array e g an array expression ALL MASK TRUE if all elements of MASK ae tnus ctherwise FALSE 269 ANY MASK TRUE if any elements of MASK are true COUNT MASK number of true elements of MASK MAXVAL ARRAY element with maximum value in real or integer ARRAY If ARRAY has zero size largest negative value on system is retumed MINVAL ARRAY element with minimum value in real or irteger ARRAY If ARRAY has size zero largest positive value on system is retumed PRODUCT ARRAY product of elements of integer real or complex array or 1 if ARRAY has size Zzero SUM ARRAY sum of elements of irteger real ar complex array ar Optional argument DIM All these functionstake an optional second argument DIM Ifitis presert the operation is performed on all rank one sections spanning through dimension DIM and returns an array of rank reduced by 1 E g INTEGER A 2 3 RESHAPE 1 2 3 4 5 6 2 3 PRINT SUM A 2 produces the output 9 12 Optional argument MASK MAXVAL MINVAL PRODUCT and SUM take MASK as a third optional argument The operation is then appliedto elements of ARRAY corresponding to true elements of MASK which must obviously have the same shape
349. ogram units Mod sub module subprogram Int subs internal subprogram Ext sub external subprogram Module Mod sub Main program Int subs Int subs Mod sub Ext sub Int subs Int subs MODULE MyMod INTERFACE SUBROUTINE SWOP U V REAL U V END SUBROUTINE END INTERFACE END MODULE which may be accessed with the statement USI The USE statement 96 E MyMod in tte calling program We have seen that the USE statement allows access to entities in a module There are two special forms of the US TE may be inco example two in module entity m E statement which affect the mode of access nveniert or impossible to use the name of a particular entity in a module For dependertly written modules may each have a subprogram withthe same name Ora ay have along and unwieldy name Module entities may be renamed for use inthe host program u named YourPl nder the new name E g ifthe module YourMod has a subprogram or variable USE E YourMod MyPlonk gt YourPlonk The general form is aru F amy US rename list module name where each iten in rename list is of the fam new name gt original name onk it may be renamed for use under the name MyPlonk as fallows Any number ofrenames may appear inthe list This use is not really recom mended and should on
350. olescence warning should be avoided they could well disappear during revision for the next standard Chapter 1 Getting Going 1 1 Introduction 1 2 Fortran 1 3 Running Fortran Programs e Greetings e AIDS cases e Compound interes Chapter 1 Summary Chapter 1 Exercises 1 1 Introduction In the period since first became an undergraduate student some 25 years ago have been fortunate enough to witness the remarkable revolution in computer technology which future historians will surely regard as one of the outstanding features of the twentieth century The first computer programmed occupied a large room Only one person could use it at a time by pressing an impressive array of switches and programs had to be punched on cards Its fast memory could store about 240 numbers Its slow memory could hold a few thousand numbers and was located on a rotating drum which you could hear ticking as it spun As technology advanced and computers became more powerful they also became much smaller From occupying a whole room they now only require part of a desk a lap or even a palm They have banded together to form networks and during an average working day it is not uncommon to send electronic mail messages around the world and to connect directly to a computer on the other side of the world You may not have used a computer before except possibly to play games but you are probably familiar with using a calculator The simples
351. ons counter not found yet first record last record 1 You can addthis subroutineto the program Student_Records of the last section and implement at from the subroutine UpDate with the following template CALL BinSearch 1 Item RecNo IF RecNo gt 0 THEN PRINT Item found at record RecNo update record RecNo ELSE PRINT Item not found END IF Figure 12 1 A file STUDENT REC and its keyed file MARKS REC STUDENT REC MARKS KEY Record Name Mark RecNum KeyField 1 Jack 23 3 69 2 Ann 34 4 76 3 Bill 89 2 a4 4 Jim 76 1 23 12 4 Keyed Files This section is a little involved if you are new to programming you might like to come back to it later An obvious extension to the program Student Record in Section 12 2 is to sort a particular offering into order of merit andto save the sorted file Ifthe records inthe data file arelong i e an array of offerings inthe Mark component this can be both time consuming because of all the swopping involved and risky disk errors are more likelyto occur during the rewrite of a large file The concept of a keyed file provides a neat solution to bcth these pctential problems For ease of reference let s callthe database file STUDENT REC Suppose we wantto sortthe Mark component inthe file We really only needthe Mark componert the key field of each student plus arefe
352. or whom these six characters are the same E g Napoleon Onaparte could get the studert number ONPNAPOO1 while Charles Wu could gt WXXCHAOO1 Write a program which reads a studert s surname and first name in some convenient way and prirts out her student number you can assume the suffix 001 for everyone 11 8 Sometimes it is convenient to pack character and numeric data into strings Such strings need to be unpacked again Write a program to read a line of text containing a student s surname and initials terminated by a comma and followed by two marks separated by at least one blank e g Smith JR 34 6 78 9 The program should unpack the string into a character variable for the name and initials and two real variables for the marks 11 9 Write a program to read text fran a file and compute the average number of words per sertence and its standard deviation Assume t sentences end with full stops which occur nowhere else 11 10 Languages exhibit a characteristic lency distribution of singleleters if a large enough sample of textis analysed For example in Act II of Hamlet the blank has a frequency of 19 7 e 9 3 o 7 3 while z occurs only 14 times out of 35224 characters The blank isimportart 150 because it gives an indication of word length
353. ord is omitted u must be firs if the FMT keyword is omitted fmt must be second following u without its keyword The cther specifiers are IOSTAT integer returns a negative value if end of record encountered during non advancing input a different negative value if enc of file detected a positive value ifan erroris detected or zero ctherwise m ND n control passes to statement labelled n when end of file detected RR n control passes to statement labelled n when an error is detected labels for END and RR may be the same if END and ERR labels are n specified and an exception occurs the program will crash unless IOSTAT is specified m REC integer specifies record number to be read during direct access NML name replaces the FMT specifies name isthe name specifiedin aNAMELIST group ts g READ 2 REC 75 IOSTAT IO Student Gl In addition non advancing input may be specified with ADVANC this case two additional specifiers are available NO default YI Gl n lt in EOR n control passes to statement n when an enc ofrecord condition occurs SIZE rteger returns the number of characters actually read The unit specifier can be an internal fi
354. orks Try it out on the following sample cata rene mber the apostrophes because the names contain commas Able RJ 40 Nkosi NX 60 October FW 13 ELSE IF Recall the program Final_Mark in Chapter 3 To output the grade 1 2 2 3 or F of each studert s finalmark we might be tempted to replace the segment IF Final gt 50 THEN ND IF Ei with a set of simple IF statements as follows IF Final gt 75 PRINT Name CRM ExmAvg Final 1 IF Final gt 70 AND Final lt 75 PRINT Name CRM ExmAvg Final 2 IF Final gt 60 AND Final lt 70 PRINT Name CRM ExmAvg Final 2 IF Final gt 50 AND Final lt 60 PRINT Name CRM ExmAvg Final 3 IF Final lt 50 PRINT Name CRM ExmAvg Final F the logical operator AND is explained fully below Whilethis works it is inefficient and may waste precious computingtime There are five separate IF statements The logical expressions in all five e g Fin gt 75 haveto be evaluated for each student although we know that only one can be true a student cannot get a firt class pass and also fail The following is a more efficiert way of coding the problem For good measure we will also count how many passed inthe first class how many inthe second class and so on The integer variables Firsts UpSeconds LowSeconds Thirds andFails represent the number of students in each of these respective c
355. ort circuitedt wo thermionic valves in one of the earliest computers This primeval charcoaled bug took days to find The process of detecting and correcting such errors is called debugging There are four types of errors e compilation exors e run time exrors e errors of logic e rounding ero Inthis chapter we deal withthe sort of errorsthat can arise withthe programming we have done so far 80 7 1 Compilation Errors Compilation errors are errors in syntax and construction like spelling mistakes are picked up by the compiler during compilation the process whereby your program is translated into machine code They arethe most f nt type of error The compiler prirts messages which may or may not be helpful when it encounters such an error Generally there are three sorts of compiler errors e rdiinary errors the compiler will attempt to continue compilation after one or more of these errors has occured e g missing ENDIF statements e f al errors the compiler will nct attempt further compilation after detecting a fatal eror eg Program too complicated too many strings e warnings these are not strictly errors but are intended to inform you that you have done something unusual which might cause problems late eg Expression in IF construct is constant or that you have used an obsolescent feature e g
356. othat we can subsequently search through them for a particular item An obvious and easy method of searching isto go through the sorted list of items one by one comparing them with the search item Th process stops either when the search item is found or when the search has gone past the place where the item wouldnormally be Thisis calleda linear search Its disadvartage isthat it can be very time consuming ifthe lit islong A much more cunning method isthe binary search Suppose you want to findthe page in ateleohone directory that has a particular name on it A linear search would examine each page in turn from page 1 to determine whetherthe name is on it This could clearly take a longtime A binary search is as follows Findthe middle of the directory by consultingthe page numbers andtearitin half By looking at the last name inthe left hand half or the first name inthe right hand half determine which half the required name isin Throw away the unwanted half and repeat the process withthe halfthat containsthe name by halvingitagain After a surprisingly low number of halvings you will be left with one page containing the required name Although this can be a little heavy on telephone directories it iNustretes the principle of a binary search quite well The method is very efficient For example my local directory has 1243 pages with subscribers names and numbers Since the method halves the number of pages ea
357. oththetype name the structure constructor for thetype and allits components are accessible only inthe host module Ifthe PRIVATE statement appears inthe definition all the components are accessible only in the host module The advantage of a publictype with PRIVATE componerts istha changes may be madetothetype definition without affectingthe code which accesses it Ifthe derivedtype is only used internally by the module the access qualifier should be PRIVATE preverting unintentional use of its name outside the module Objects and sub objects The time is right for a few more definitions We have seen that components of derivedtype may be arrays E g thetype First Year defined at the beginning of the chapter has a component REAL DIMENSION 20 Marks Marks Arrays of derivedtype may also be ceclared eg TYPE First Year DIMENSION 100 Class An element ofthis array say Class 17 is regarded in Fortran 90 as a scalar because itisina sense a single structure although it has a component which is an aray it could even have a componert which is ancther cerived type An entity which is not part of a bigger entity has a name andis calleda named object Itssub objects have designators consisting of the name of the object followed by o
358. our own denominations if necessary 5 4 Write aprogram forthe general solution of the quadratic equation ax bx c 0 Use the structure plan developed in Chapter 4 Your program should be able to handle all possible values of the cataa h and c Try it out on the following values of a bande a 1 1 1 Complex rocts wo 2 4 2 equal mqs of 1 0 Q 2 2 12 ros of 2 0 and 3 0 Rewrite your program with complex types so that it can handle complex roots as well as all the other special cases 5 5 Develop a structure plan for the solution of two simultaneous linear equations Le two straight lines Your algorithm must be able to handle all possible situations viz lines which are irtersecting parallel or co incident Write a program to implement your algorithm and test it on some equations for which you know the solutions eg x y 3 2x y 3 x 2 y 1 Hint begin by ceriving an algebraic formula forthe salution of the system 56 ax tby c ll Hh dx ey The program should read the coef ficierts a b g q eand f 57 Chapter 6 Loops Chapter 6 Introduction 6 1 Deterministic Repetition Factorials Binomial coefficient Limit of a sequence Complex transfer function 6 2 The DO in General 6 3 DO with Non integer Increments 6 4 Nested DOs Loan Repayments 6 5 Non deterministic Loops A guessing game
359. own Hahn Brian D Fortran 90 for Scientists and Engineers l Title 005 13 ISBN 0 340 60034 9 All rights reserved No part of this publication may be reproduced or transmitted in any form or by any means electronically or mechanically including photocopying recording or any information storage or retrieval system without either prior permission in writing from the publisher or a licence permitting restricted copying In the United Kingdom such licences are issued by the Copyright Licensing Agency 90 Tottenham Court Road London WIP 9HE Whilst the advice and information in this book is believed to be true and accurate at the date of going to press neither the author nor the publisher can accept any legal reaponsibility or liability for any errors or omissions that may be made Printed and bound in Great Britain for Edward Arnold a division of Hodder Headline PLC 338 Euston Road London NW1 3BH by the University Press Cambridge Foreword The present text arises from an extensive revision of our previous book Advanced Methods of Data Exploration and Modelling Since so much new material is included particularly in those sections dealing with linear models and latent variable models we thought it appropriate to regard the work as new rather than simply a second edition Consequently we have taken the opportunity to give the book a more appropriate title Preface The Fortran 90 standard represents the first significant change
360. pinning coins there is a certain probability of being in any of the states at a given moment and also a probability of changing from one state to another If the probability of moving from one state to another depends on the present state only and not on any previous state the process is called a Markov chain The progress of the drunk sailor in Chapter 14 is an example of such a process Markov chains are used widely in such diverse fields as biology and business decision making to name just two areas A random walk This example is a variatim on the random walk problem of Chapter 14 A st has six irtersections A drunk man wanders down the strect His home is at intersection 1 and his favourite bar at irtersection 6 At each irtersection octherthan his home orthe bar he moves inthe direction of the bar with probability 2 3 and inthe direction of his home with probability 1 3 He never wanders down a side street If he reaches his home or the bar he disappears irtothem never to re appear when he disappears we sayin Markov jargon that he has been absorbed We wouldlketo know what arethe chances of him ending up at home orinthe bar if he starts ata given corner cther than home or the bay obviously He can clearly be in one of six states with respect to his random walk which can be labelled by the irtersection number where state 1 means 215 Home and state 6 means Bar We can represent
361. pproach taken is a problem solving one developed over many years of teaching programming to first year university students with no computing experience The computer is presented as a tool probably the most exciting one of the 20th century for solving interesting real world problems and examples from many areas particularly science and engineering are discussed The technicalities of each new FORTRAN construction are therefore generally presented only after motivation by the posing of a suitable problem Since the objective of this book is to enable you to solve problems using a computer the first 12 chapters are in a sense a preparation for the final three In these later chapters you will be introduced to some modern computer applications such as simulation modelling and numerical methods There are also a large number of exercises involving a variety of applications Most of these have solutions provided Those that do not have solutions may be suitable for use as class projects in a teaching situation Secondly structured problems are developed throughout The beginner is shielded from the devastating effect of the GOTO statement until well into the text When it is introduced the use of GOTO is encouraged in one well defined situation only this feature appears to be unique in all the vast literature on FORTRAN Thirdly emphasis is laid throughout the book on what has come to be called programming style and guidelines for writing clear
362. prints the iteration court TRIPS before computing and printing the stone s position every dt seconds Notethat t must be explicitly updated inthe DO block now since I is used purely as a counter REAL PARAMETER G 9 8 REAL dT S Ty TStart Tead REAL U 60 INTEGER I TRIPS READ TStart TEnd dT TRIPS INT TEnd TStart dT SPACING dT 1 PRINT TRIPS T TStart DO I 1 TRIPS S U T G 2 T T PRINT I T S T T adr END DO A further interesting problem arises Suppose we still want to compute s f every dt seconds but only wart to prirt it every h seconds this isa common problem in numerical analysis where the step length dt might be very small Given that we want output on the first iteration we therefore have to skipthe next h dt iterations before prirting again Because the DO variable I starts at 1 this means that we want output whenever I 1 is an exact multiple of h dt This can be achieved by replacing the PRINT above with IF MOD I 1 INT H dT SPACING dT 0 PRINT I T S where the same allowance has been made for rounding exror and the value of h must be input Note that the loop in this problem is indeed deterministic we could determine our own iteration court in advance Although this isthe recom mended way of handling nomirteger increments there is ancther salution which
363. r NumTerms terms INTEGER M N READ M N DO WHILE M N DO WHILE M gt N N END DO PRINT HCF is M 6 14 The Chapter 8 R R P FAL X EAD RINT CONTAINS FUNCTION final payment is 157 75 inthe 54th month don t forget the irterest inthe laxmonth X X Expo X F Expo X R EAL Expo Term EA INTENT IN X 17 R IN EX K Te DO EN D N 0 Fl m N 7 EA ry Py I Ou H Expo FUNCTION NCTION Normal Normal EG fe 1 rm 1 WHILE erm ER K ABS Term gt le 6 Term X K Expo Term T D DO N K Expo X R T A AL A A INTENT IN X iA 0 4361836 B 0 1201676 C 0 937298 Pi 3 1415927 EG F 1 DO CONTA REC R X X 2 Z S9RT 2 PI 1 0 3326 X Ovo SRIF Aree Te B ope 8 Ee Ce Oe Th ee 3 UNCTION Normal RINT R N Ly 20 I4 F9 1 N Fibo N INS URSIVE EA T FUNCTION Fibo N R ESULT F INT IF F EGE N Hi F 0 Fl 0 m mj O 4 iw IF UNCTION Fibo Fibo N 1 Fibo N 2 ENSION 100 IpI 1 50 2 I Num 100 1 281 9 3 REAL INTEGER
364. r but there will still always be some value of t where the error exceeds some acceptable limit We may ask why Euler s method works so well with the skydiver but so badly with the bacteria By using the Newton quotient each time in Euler s method we are actually assuming that the derivative changes very little over the small interval h i e that the second derivative is very small Now in the case of the skydiver by differentiating Equation 16 5 again with respect to time we see that d v dt 2kv dv dt which approaches zero as the falling object reaches its terminal velocity In the bacteria case the second derivative of N t is found by differentiating Equation 16 10 d N dt rdN dt r N t This is far from zero at t 10 In fact it is approaching three million The Newton quotient approximation gets worse at each step in this case There are better numerical methods for overcoming these sorts of problems Two of them are discussed below More sophisticated methods may be found in most textbooks on numerical analysis However Euler s method may always be used as a first approximation as long as you realize where and why errors may arise A Predictor Corrector Method 236 One improvement on the salution of dy dx fix y y0 given is as follows The Euler approximation which we are gaing to dencte by an asterisk is given by Via hf xx Yx 16 12 ESA on the right hand side Surely
365. r matrix may be represerted by a dynamic array of increasing size Run the following example which is adapted from Metcalf and Reid TYPE ROW REAL DIMENSION POINTER R END TYPE INTEGER PARAMETER N 4 TYPE ROW DIMENSION N S T arrays of type ROW i e matrices DO I 1 N ALLOCATE T I R 1 I1 allocate storage for each row of T END DO T I R 1 I 1 assign values to matrix T oe I array assignment S I R I 2 assign values to matrix S I S R I print matrix T You may be surprised to find that T has taken the value of S This is because the assignment SE involves structures whose components are poirters The rule is that pointer assignment occurs for the poirter components The above assignment is therefore equivalert to the poirter assignments for allthe components Since allthe componerts of S and T are poirters this effectively makes S an alias of T which is why T takes the same value as S inthe above example Note that this representation uses only half the starage of conventional two dimensional arrays Sorting structures We saw in Chagter 12 how to use a key fileto sort structure variables on a particular component in order to reduce the amount of swopping involved An al ive approach is to use an array of poirters se up as an array of structures with a poirter component
366. r old fashioned and tends to be frowned upon in certain computing circles However engineers often prefer this visual method so forthat reason and for historical interest some examples are given here Suppose we wartto write a program to convert atemperature on the Fahrenheit scale where water freezes and boils at 32 and 212 respectively tothe more familiar Celsius centigrade scale Th flowchart forthe problem is in Figure 4 1 The main symbols used in flowcharts are explained in Figure 4 2 Figure 4 1 Fahrenheit to Celsius conversion input Farenheit 4 C 5 F 32 9 Compute Celsius Output 2 Quadratic equation When you were at school you probably solved hundreds of quadratic equations of the form ax bx c 0 The complete algorithm for finding the solution s x given any values of a b and c is flowcharted in Figure 4 3 Newton s method for square rooting In Chagter 3 we wrote a program Newton to find square rocts which used a DO loop There is no universally accepted way of flowcharting a DO loop but one way isto usethe elongated diamond to give the conditions under which the block of statements in the loop the body of the loop is executed with a small circleto mark the end of the loop as shown in Figure 4 4 Note that the contents of the boxes can be either Fortran statements or more general mathematical expressions 4 2 Structure Plans
367. ram We have seenthe onlytwo situations where a unit number is not required The PRINT normally expects to output to the terminal and the first form of READ above normally expects to read from theterminal In such cases the terminal is calledthe standard I O unit Your system may allow you to change the standard unit The unit specifier u when itis required may be of three forms an integer expression an asterisk which impliesthe standard input unit or a character variable in the case of an internal file see below 132 The remaining specifiers are optional andmay be in any order If IOSTAT is specified ios must be an irteger variable After execution of READ ios has different system dependent negative values depending on whether an end of record or enc of le condition occurred a positive value if an error was detected or the value of zero ctherwise The presence of IOSTAT prevents a crash if an exception occurs Further details are given in Appendix B 10 5 Formatte d WRITE The general form of the WRITE statement for formatted output is WRITE UNIT u FMT fmt IOSTAT ios ERR errorlabel list The specifiers have the same meanings as inthe READ statement The output device ma y be selected during program execution You may be developing a large
368. ram segment the logical variables S1 and S2 represert the state of two switches ON true OFF false and L represerts the state of a light The program simulates the circuits in Figure 5 1 where the switches are arranged either in series or parallel LOGICAL L S1 S2 READ S1 S2 L S1 and S2 series IL Sl or 52 parallel PRINT L When the switches are in series the light willbe on only if bcth switches are on This situation is reoreserted by Sl and S2 When the switches are in parallel the light will be on if one or both of the switches is on This is represented by Sl or S2 Bit manipulation functions Some programming languages such as Pascal and C have operators called bitwise operators which operate directly on the bits of their operands These are usually discussed in the context of logical or Boolean variables In Fortran 90 their counterparts are the bit manipulation intrinsic functions which operate on the bits of their integer arguments These are described in Appendix C 5 3 The CASE Construct The CASE construct is similarto IF t allows selection between a number of situaticns or cases based on a selector In such cases it is more conveniert than IF Consider the following program segment 53 CHARACTER CH DO READ CH PRINT ICHAR CH IF CH EXIT IF CH
369. re blocks of statements If the condition is twe blockl is executed and not blockE otherwise blockE is executed and n blockl The ELSE part is optional and may be left out Executi on continues inthe normal sequential way with the next statement a fter END IF The condition may be formed from numeric expressions with the relational operators such as lt lt such as equals and not equals and fran other logicalexpressions wi hthe logical operators NOT AND and OR These are all discussed fully withthe in Chapter 5 The F statement A shorter form of the IF construct isthe IF statement TE Ge ondition statement most general form of IF Inthis case only a single statement is executed ifthe condition is true Nothing happens if it is false The word construct implies a construction with morethan one statement and hence morethan on keyword 3 3 Characters A glaring shortcoming of the above program is that the studerts names are neither read nor printed To remedy this we make use of character variables Make the following changes to Final Mark Insert the statement CHARACTER Len 15 Name Name irto the declaration section Change the statement that prints the heading PRINT READ x Name CRM Exam Avg Final Mark Change the READ statement 1
370. rence field to point tothe student s name inthe original file STUDENT REC oncethe key field has been sorted We therefore create a key file MARKS KEY the records of which willbe structure variables of type Key TYPE Key INTEGER RecNum INTEGER KeyField END TYPE Key The component KeyField has the mark to be sorted while the component RecNum gives the position record number of the student with that mark in STUDENT REC Now a sort need only be performed onthe much smaller file MARKS KEY Figure shows the contents of both files after sorting MARKS KEY The RecNum field givesthe names of the studentsin order of mert 3 Bill 4 Am 2 Ann and 1 Jack The program KeyTest below reads STUDENT REC and createsthe key file MARKS KEY Italso copies the records of the key file irto the array KeyArr which is passed to the subroutine Key Sort Thisisan amendment of the Bubble Sort subroutine in Chapter 9 only amended lines are shown After sorting KeyArr is written back to MARKS KEY The sorted key file is then used with the original database STUDENT REC to write the names of the studerts and marks in order of merit PROGRAM KeyTest IMPLICIT NONE INTEGER PARAMETER NameLen 20 INTEGER PARAMETER MaxStu 100 TYPE Key 16
371. ression rounded if necessary e The number of dimensions of an arrayisits rank An arraymay have upto seven dimensions A scalar has a rank of zero e The number of elements along a dimension of an array isthe extent of the dimension e The sequence of the extents of an array is its shape e An array may be passed as an actual argument to a subprogram The dummy argument must have the same shape Ifthe corresponding dummy argument is an assumed shape array it will take on the shape of the actual argument e A dynamic variable which may be an array is specified withthe ALLOCATABLE attribute and may be allocated memory while a program is running The me mory may be ceallocated later e A dummy argument may nct be allocatable e A rank one anay consart may be formed with an array constructor e An implied DO may be used in an array constructor e An array sia is a subarray e A section subscritt given by a rank one irteger expression is a vector subscrict e Arrays withthe same shape are conformable e A section is conformable with any array of the same shape e A scalaris conformable with any array e Array expressions may be farmed from conformable arrays e Array expressions may be assigned to conformable arrays e When an elemental intrinsic function takes an array argument the function is appliedto each element of the array e The WHERE construct cortrals operations on arr
372. riable X Having each data value on a separate line in the file is rather cumbersame this is required by th separate execution of each READ 1 X I inthe DO loop Fortran allows the use of an implied DO to read or prirt all or part of an array Simply replace the entire DO construct in the program with READ 1 X I I1 1 N Note that the syntax requires parentheses around the implied DO 9 2 Basic Rules and Notation The array is our first example in Fortran 90 of a compound object i e an object which can have more than one value Arrays can be fairly complicated creatures Only the basics are mentioned here more advanced features will be introduced Jater The statement REAL DIMENSION 10 X declares X to be an array or list with 10 real elements dencted by X 1 X 2 X 10 The number of elements in an array is calleditssize 10 inthis case Each element of an array is a scalar single valued Array elements are referenced by means of a subscript indicated in parentheses after the array name The subscri t must be an integer expression its value must fall within the range defined in the array declaration So X I 1 isa valid reference for an element of X as declared above aslongas I 1 isinthe range 1 10 A compiler error occurs ifthe subscrig is out of range By default arrays have a lower bound of
373. riables are described in comments The user defines the model differential equations inthe extemal subroutine DEqs SUBROUTINE DEqs F evaluates RHS of DEs USE DrGlobal IMPLICIT NONE REAL INTENT OUT F REAL POINTER Prey Pred p q Yr 8 model equations are dx dt Fl px qxy dy dt F2 rxy sy Prey gt X 1 symbolic aliases Pred gt X 2 reduce likelihood of errors p gt Params 1 Val q gt Params 2 Val r gt Params 3 Val s gt Params 4 Val F 1 p Prey q Prey Pred F 2 r Prey Pred s Pred END SUBROUTINE DEqs DEqs evaluates and returns the right hand sice of the th differential equation inthe th element of al the array F To allow the userto use more meaningful symbolic names for parameters and variables liases are set up bet ween the symbolic names andthe system variables declared in DrGlobal 239 This is why DEqs must access the module DrGlobal and why the currert values of the model variables must be held inthe array X The use of aliases makes it much easier to code laroe models The module DrUtils must access DrGlobal and looks as follows MODULE DrUtils Driver utility subroutines USE DrGlobal IMPLICIT NONE INTERFACE SUBROUTINE DEqs F REAL F END SU
374. ring e g 10 FORMAT 24HWe must count carefully The drawback isthat you must court the number of characters inthe string itis very easy to make a mistake Control edit descriptors These edit descrictors enable you to position output precisely start a new record skip columns on input amp c Embedded blanks in input fields are treated either as zeros or as nulls the default The default is overridden by the BN blanks null and BZ blanks zero edit descrictors The new mode holds for the rest of the format specification or until explicitly changed E g the input string 163163 is read under BN 13 BZ I3 asthetwo values 13 and 103 There are three descriptors which contralthe leading signleading sign on output A leading minus is prirted by default The SP sign prirt edit descrictar causes leading positive signs to be printed The SS sign suppress descritor suppresses leading plus signs while SP is in effect andthe S descrictor restores the default option E g the value 99 writtenthreetimes under SP I3 SS I3 S 13 appears as 99b99b99 A sign descritor holds for the rest of the format specification unless changed by ancther sign descritor Scale factors ofthe form kP may be applied to input of real quantities underthe E F EN ES and G edit descrittors k is an integer constant specifying the scale factor Any quantity without an exponent
375. rly all have the same shape i e the same extent along conesponding dimensions Matrix multiplication Probably the most important matrix operation is matrix multiplication Tt is used widely in such areas as network theory solition of linear systems of equations transformation of co ordinate systems and population modelling for examples The rules for multiplying matrices look a litt weird if you ve never seen them before but will be Justified by the applications that fallow 203 Whentwo matrices A and B are multiplied together their product is athird matrix C The oper is written as C AB Lu on andthe generalelement Ci of Cis formed by takingthe scalar product of the ith row of A withthe jth column of B Ji are the compon The scalar product of two vectors x and y is Miva te Mate where Xi and nts of the vectors It fallows that A and B can only be successfully multiplied inthat order ifthe number of columns in A isthe same as the number of rows in B The general defini ion of matrix multiplication is as follows If Aisa nxm matrixand Bisa mx p matrix their product C willbe a n xp matrix such that the general element Ci of C is given by m Cj by k 1 commutative Example 1 2 5 6 x 3 4 0 1 Note that in general AB is not equal to BA matrix multiplic
376. rms of input possible under the F descrictor If the input is in standard scientific notation or ifthe E is omitted from the standard form and the exponent is signed the d specifier is again ignored E g 12 345E 2 12 345 2b is read under F9 1 as 0 12345 The E edit descrittor hast wo forms For both of them the rules for input are the same as those for the F descriptor On output Ew d produces a mantissamantissa significand of d digits with an absolute value lessthan 1 overa field of w This must include room for a possible sign the decimal poirt and an exponent of four characters consisting either of E followed by a sign andtwo digits or of a sign and three digits The form with E is n used ifthe magnitude of the exponent is greater than 99 E g 1 234 times 10 23 is written under E10 4 asb 1234E 24 b 1234 024 The other form of the E descrictoris Ew dEe where e determines the number of digits to appear in the exponent field This form is mandatory for exponents with a magnitude greaterthan 999 E g 1 234 times 101 is written under E12 4E4 as b 1234E 1235 The EN engineering edit descrixtor is the same as the E descriptor except that on output the exponert is divisible by three the mantissais greaterthan or equalto 1 andlessthan 1000 andthe scale factar see below is ignored E g 0 00217 is writte
377. ructure easier to follow uated If i ntral passes to the next t is true the END IF If none of the logical expressions is true the statements in blockE are executed Clearly the logical expressions should be arranged so that only one of them can be true amp atime There may be any number of ELS E IFs o none amp all ht there may be no more than oe ELSE An IF construct may be optionally named as an aid to the reader usually to clarify complicated nesting GRADE eg IF PRINT F LSE PRINT Final gt 50 Pass GRADE Fail THI END IF GRADE ELSE or F ELSE IF bl named and must ke given Note that ncthing may follow the keyword THEN on the 50 ock may only be named ifthe corresponding IF and the same name The name must be a valid and unique Fortran name inst line of the construct END IF blocks are Nested IFs When IF constructs are nested the positioning of the END IFs is crucial as this determines to which IFsthe ELSE IFs belong An ELSE IF or ELSE belongstothe most recently opened IF which has not yet been closed To illustrate consider once again program ming the solution of the ubiquitous quadratic equation ax bx c 0 Ik is necessary to check if a 0 to prevent a division by zero
378. s 12 3 A Binary Search 12 4 Keyed Files 12 5 Hashing Chapter 12 Summary Chapter 12 Exercises Chapter 12 Introduction So far we have restricted ourselves to the five intrinsic data types of Fortran 90 We have seen how to use simple variables and arrays of these types to solve a variety of problems We may however soon discover situations where it would be very convenient to handle more complicated collections of data as single units Arrays for example are restricted in that all their elements must be of the same type One of the major advances of Fortran 90 over previous versions is that you now have the freedom to design data types of your own Such data types are called derived In this chapter we will discuss derived data types which may be used to define structures 152 12 1 Structures As an example let s consider the problem of maintaining studert records We have often used examples where we have processed say a studert s name and some marks In a real situation additional information would be needed address registration and telphone numbers and maybe even date of birth and gender You can define a type to encapsulate all this data for one person as follows TYPE First Year CHARACTER 20 Name includes initials etc CHARACTER 20 DIMENSION 4 Address 4 lines for address CHARACTER 10 Telephone CHARACTER 9 Re
379. s below Newton s method can also find complex rocts but only if the starting guess is complex The 2 following program finds a complex rot af X x 1 0 PROGRAM ee cca oa COMPLEX X READ X PRINT 2A10 Re x Im x PRINT N 1 DO WHILE ABS F X gt 1E 6 AND N lt 20 X X F X DF X 225 PRINT 2F10 4 X N N 1 END DO CONTAINS FUNCTION F X COMPLEX X F Be K A eG he END FUNCTION F FUNCTION DF X COMPLEX X DF DF 2 X 1 ND FUNCTION DF PROGRAM ComplexNewton 0 Fl m N If you start with 0 2 Le 24 1 x converges rapidly Re x Im x 0 2941 1 1765 0 4511 0 8975 0 4982 0 8653 0 5000 0 8660 0 5000 0 8660 Since complex rocts occur in complex conjugate pairs the her roct is 0 5 0 866 Note that a complex consart must be enclosed in parentheses for lis directed input You can use this version to find real roots also except you must then obviously give real starting values The Bisection method Consider again the problem of salving the equation f x 0 where f x x x 3 We attempt to find by inspection or trial ancterror two values of x call them Xr and XR such that fx and fxr have different signs i e fa Jf Xr lt 0 If we can find two such values the root must lie somewhere inthe interval bet ween them since f x changes sign o
380. s and name isthe optional construct name expr3 is optional with a default value of 1 The expressions expr expr2 and expr3 are calledthe DO parameters The DO variable is initialized to expr beforea decisionismade whether or notto loop accordingto the formula below On compleion of each loop expr3 is added tothe DO variable again before deciding whether or not to Loop Ik follows that after completion of the DO construct the DO variable will not have the value it had during the last execution of the block E g inthe first segment above the final value of I is 8 The number of iterations of aDO construct is given by the formula MAX expr2 expr1 expr3 expr3 0 where MAX is the intrinsic function returning the maximum of its arguments Since MAX returns a value which has the same type as its arguments the value returned in this case willbe the value of the expression truncated if necessary ar zero whichever is larger This formulaiscalledthe iteration count or the trip count of the DO loop You should verifythat the iteration counts forthe four segments above are 3 0 5 and 3 respectively Note that it is possible forthe DO block noto be executed at all This is called a zero trip loop and will cocur whenever the first argument of MAX inthe formula evaluates to a non positive quantity DO JT J KL e TfL is positi
381. s all characters supported by your computer system with the exception of the contral characters The standard requires that the default kind satisfies a certain collating sequence This isto enable sorting of characters which isdiscussed in Chapter 11 33 Other character sets e g Greek may be supported by your system andthese would have different kind parameters Inthe case of character constarts the kind parameter if any precedes the constant So if the named constarts ASCII and GREEK had the values of the default and Greek kind constarts of those kinds could be written as ASCII abcde GREEK apyde We saw inthe case of integers and reals above that the kind parameter may be specified with a type parameter Sincethe length of a character variable may also be specified on declaration character is the only type to have two type parameters cne for length and one for kind Examples CHARACTER LEN 10 KIND GREEK Greek Word CHARACTER LEN 10 English Word default kind CHARACTER KIND GREEK Greek Letter default length of 1 CHARACTER 10 GREEK Greek Word Note that the specifiers LEN and KIND are optional However if only one unnamed parameter is given it istaken to be the length n the kind The function KIND alsotakes
382. s obliquely on a ionary sphere of mass m the direction of the blow making an angle amp with the line of motion of the impinging sphere Ifthe coefficient of rescintion is e t can be shown that the impinging sphere is deflected through an angle J such that m 1 e tana m em m m tan a tan p Write a program to read values of My M e and amp in degrees and to compute the angle J in degrees 40 Chapter 4 Program Preparation Chapter 4 Introduction 4 1 Flowcharts e Quadratic equation e Newton s method for square maing 4 2 Structure Plans e Quadratic equation 4 3 Structured Programming with Procedures Chapter 4 Summary Chapter 4 Exercises Chapter 4 Introduction Our examples so far have been very simple logically since we have been concentrating on the technical aspects of writing Fortran statements correctly However real problems are far more complex and to program successfully we need to understand a problem thoroughly and to break it down into its most fundamental logical stages In other words we have to develop a systematic procedure or algorithm for solving the problem There are a number of methods which assist in this process of algorithm development In this chapter we outline two flow charts and structure plans which have already been mentioned briefly 41 4 1 Flowcharts This approach is rathe
383. s of students write a test and each student s name maximum of 15 characters and mark is erteredin a datafile Assume there are no negative marks We wantto writea program which prirts out the name ofthe student withthe highest mark together with his her mark We are assuming that there is only one highest mark The problen of whatto do whentwo or more students share the top mark is discussed in Chapter 9 A first level structure plan for this problem could be 1 Start 2 Find top student andtop mark 3 Prirt top student andtop mark Step 2 needs elaborating so amore detailed plan might be 1 Start 2 Initialize TopMark to get process gaing 3 Repeat for all Read Name and If Mark gt TopMark Replace TopMark with Replace TopName with Name 4 Prirt TopName and TopMark 48 students Mark Mark 5 Stop The program for a sample class of 3 students is IMPLICIT NONE INTEGER I student counter REAL Mark general mark CHARACTER 15 Name general name REAL TopMark 0 top mark can t be less than zero CHARACTER 15 TopName top student OPEN 1 FILE MARKS DOSL As 3 READ 1 Name Mark IF Mark gt TopMark THEN TopMark Mark TopName Name END IF END DO PRINT Top student TopName PRINT Top mark TopMark Work through the program by hand for a few turns to convince yourself that it w
384. s the length of the variable being read If wis lessthan len the left most w characters are read padded with blanks on the right E g under A5 the input string NAPOLEON is read into NAME as declared above as NAPOLDDbb However and this isthe strange bit if w is greaterthan len the right most len characters are read So under A8 for example the string NAPOLEON is readinto NAME as APOLEON One would have expected the leff most characters to be read outindent Finally there are the general Gw d and Gw dEe edit descriptors which may be used for any of the intrinsic datatypes These descriptors are useful for printing values whose magnitudes are not well known in advance Where possible values are output under the equivalert F descriptor otherwise the equivalent form with E is used The character string edit descriptor A character consart a string of characters enclosed in apostrophes or quotes may be output by embedding it in a format specification as we have already seen eg PRINT 10 10 FORMAT Fortran 90 is the language for me For completeness we should mention the obsolescent H edit descrictor Ik was named in honour of Hollerith who invented punch cards to process a census inthe United States duringthe last century An output character string without delimiters may be preceded by an nH descrictor where the irteger constant n isthe number of characters in the st
385. same as 3 It only needs to be separated by a comma from a preceding descrixtor if it has a repeat court Colon editing stops format control ifthe are no more items in an I O lis In particular itis useful in preverting unwanted character strings fram being prirted E g the statements PRINT 10 X I I 1 N TO FORMAT UXT stg D2 oh XB TED gs KS ag ES produce the outout XIs 1 when N has the value 1 Without the colons the output would have been X1 1 X2 Note that the colons do n need to be separated from neighbours by commas Repeat counts The data edit descrittors described above as well asthe new record slash descrictor may all be preceded by a repeat count inthe form of an integer constant A repeat count may be appliedto a group of edit descriptors enclosed in parentheses and may be nested e g 3 2F6 2 2 12 313 Tf a format specification without any items in parentheses is completed before the I O list is exhausted a new record begins andthe format specification is repeated Further records begin inthe same way untilthe I O litis exhausted E g the following code prints an array of 100 elements 20 elements per Ine PRINT 10 X I I 1 100 10 FORMAT 2013 Similarly on input anew recordistaken from the input file each time the specification is repeated Any excess input data on the record is ignored E g the co
386. see some important changes in the basics of Fortran In keeping with the spirit of the earlier edition this book is a problem solving exposition of Fortran 90 and not a technical reference manual You will therefore not necessarily find all the references to a particular topic in one place in the text e g arrays are covered in Chapters 9 and 15 as this would interfere with the informal style of the book There are however appendices with summaries of all the statements and the intrinsic procedures and a comprehensive index should like to thank the following in particular David Mackin of Edward Arnold for his helpful editorial suggestions and for arranging the loan of an FTN90 compiler Peter Anderton of The Numerical Algorithms Group for the loan of the compiler the University of Cape Town for leave in order to write this book and for financial support for the project my long suffering colleagues for leaving me alone while was writing and my wife Cleone who patiently reminds me when programs won t work that computers are like that aren t they Brian D Hahn Department of Applied Mathematics University of Cape Town Rondebosch South Africa June 1993 Preface to Problem Solving with FORTRAN 77 So many books on FORTRAN have been written that the appearance of yet another one seems to require some justification There are three particular areas where this book can claim to make a distinctive contribution Firstly the a
387. sible generic name in which case all subprograms withthis generic name are invokedthrough it Inthis way the intrinsic functions may be extendedto accept arguments of a derived type Tf you want to overload a module subprogram the interface is already explicit so it is incorrect to specify an irterface body Instead you must include the statement MODULE PROCEDURE procedure names inthe interface block where procedure names are the procedures subprograms to be overloaded So ifthe subroutines SwopReals and SwopIntegers were defined in a module the interface block would be INTERFACE SWOP MODULE PROCEDURE SwopReals SwopIntegers END INTERFACE This irterface block could be placed inthe module itself Try it We will see later how to overload irtrinsic operetors and the assignment in order to extend these operations to derived types 8 9 Stubs A large program willhave many subprograms To plan and codethem allbefore compiling is asking for trouble A useful trick is to use stubs which define the subprogram names but do nothing at first Then fillthe stubs in one at atime compiling after each fillin That way it s much easierto catch all the compiler errors You can initially define the subprograms as internal with all local variables declared moving them out to modules as they are completed This obviates having to recomp
388. sic subroutines Chapter 3 Summary Chapter 3 Exercises Chapter 3 Introduction So far we have seen how to read data irto a Fortran program how to do some arithmetic withthem and how to output answers In this chapter we look at two powerful constructions which feature in most real programs DO and IF We also look atwo morir and discuss the concept of kind The chapterends with a brief i trinsic types character and complex troduction to intrinsic functions 24 3 1 DO Loops Run the fallowing program INTEGER I ye eal D ye To get some random numbers instead replace the PRINT statement with the following two statements CALL RANDOM NUMBER R PRINT R Every time you run the new program you will get the same 10 random numbers which is rather boring To see how to get a different s amp each time you willhave to wait until Chapter 14 For a change try the following DO I 97 122 WRITE 10 ADVANCE NO ACHAR I 10 FORMAT Al END DO The form of the WRITE statement above introduces a new feature which old hands will welcome with rejoicing non advancing T O To get the alphabet backwards replace the DO with DO I 122 97 1 The DO loop o its equivalent is one of the most powerful statements in any programming language One of its simplest forms is DO I J K block END DO
389. spection All higher powers of A willalso obviously be null since ifthere are no paths of length 4 there can hardly be any that are longer In general then the element in row i and column j of the kth power of an adjacency matrix is equal tothe number of paths consisting of k arcs linking nodes i andj Coming back to our spy net work since the elements of A a the number of paths of length 1 and the elements of A arethe number of paths of length 2 etc then clearlythe sum of allthese powers 211 of A willtell us how many paths of any length there are altogether bet ween the various nodes We can therefore define a reachability matrix R forthis 5 x 5 network 2 3 4 R A A A A Risalsoa 5x 5 matrix and its elements give the tctal number of paths of communication between the agerts Doing the calculation gives us 0 0 1 0 0 1 0 3 1 1I R 0 0 000 00100 0 02 1 0 So we can read off from the reachability matrix R the fact that there are for example three different paths between Boris and Cyril but only two between Eric and Cyril the actual lengths of these paths will have been calculated in findingthe powers of A The name reachability is used because the non zero elements of R indicate who may contact whom directly or indirectly or fora general distance network which nodes can be reached from each node The reachabili
390. t amp MYOUT A 1 1 7 7 X 1 0000000 Y 3 0000000 The anay section A 3 4 andthe variable X are left unchanged Chapter 10 Summary A record can be thought of as a line of input output Format specifies the layout of a record Format may be specified by a labelled FORMAT statement by an asterisk listtdirected I O or by a character string The PRINT statement generally only handles output to the screen Implied DO lits may appear in VO lists The WRITE statement can handle output to a file or prirter The READ statement handles input from a file arthe keyboard O may be lit directed formatted or unformatted Format is controlled by edit descrixtors The OPEN statement connects a fileto a unit number to enable transfer of deta The INQUIRE statement obtains information about files unit numbers and record lengths of output lists Various specifiers such as IOSTAT END and ERR may be usedin I O statements to interoept and handle end of file conditions and possible errors Data may be transferred directly to or from a character array inthe form of an irternal file Disk files are examples of external files Files consist of records which may be formatted or unformatted Files are accessed sequentially the default or directly random access
391. t anywhere on the Line e All sdatements excep assignments tat with a keyword e A Fortrantoken is a sequence of characters forming a label keyword name constant operator or separator e Blanks shouldbe used to improve readability except inside keywords and names e Comments may be typed after the exclamation They should be used liberally to describe variables andto explain how a program works e A statement with amp as its latnomblank character will be continued onto the next line e Ther are five intrinsic dta types irteger real complex logical and character 20 e Values of each dta type are represented by literal constarts e Trteger constants may also be represented inbinary octal and hexadecimaL e Real constants are represented in fixed point or floating paint exponential form e Alphanumeric characters are the letters digits and the underscore e Names may contain upto 31 alphanumeric characters starting with a letter e A variable isthe symbolic name of a memory location e The IMPLICIT NONE statement should be used to avoid variables being given a type implicitly e A numeric variable should be declared irteger or real in atype declaration statement e Numeric expressions may be formed from constarts and variables with the five numeric irtrinsic operators which operete according to strict rules of precedence e Decimal parts are
392. t integers and reals internally The parameters of the models may vary from processor to processor An example of a model for the set of integers i represented is 267 q i 99 w x 2 7 k 1 Wi where is Oor 1 An example of the representation of reals x is p vador t22 A fk 2 oa where 7126 lt e 127 for example and TEST 1 Values for p and q could be 24 and 31 for example A base other than 2 might also be used Numeric inquiry functions Arguments may be scalars or arrays The value of the argument need n be defined DIGITS X number of significant digits in the model for real or irteger X Le p or q EPSILON X numberthat is almost negligible compared with 1 inthe model that includes real X l p ie2 27 ana HUGE X largest value inthe model that includes real or integer X Le MAXEXPONENT X maximum exponent integer in the model that includes real X ie 127 MINEXPONENT X minimum exponent integer inthe model that includes real X Le 126 PRECISION X decimal precision number of decimal places for real or complex X RADIX X RADIX base integer inthe model that includes real or irteger X Le 2 RANGE X decimal exponent range inthe model that includes irteger real or complex X 127 TINY X smallest positive number inthe model that includes real X ie 2 a
393. t of error is to perform a sensitivity analysis on the coef cierts are subject to experimental errors the solution is again meaningless One way to ficients change them allin tum by the same percentage and observe what effect this has on the solution 85 Chapter 8 Subprograms and Modules Chapter 8 Introduction 8 1 Internal Subprograms e Newton s method again e 6 Rotation of co ordinate axes e Irternal functions e Arguments e Local and global variables e The RETURN Statement e Statement functions e Irternal subroutines 8 2 The Main Program 8 3 External Subprograms e The EXTERNAL statement 8 4 Interface Blocks e When to use interface blocks 8 5 Modules The USE statement e PUBLIC and PRIVATI CI attributes 8 6 Scope e 6Scope of labels e Scop of names 8 7 Arguments e Reference arguments e Value arguments e Argumert itet e Matching type e Optional and keyword arguments e Arrays as arguments e The SAVE attribute e Subprograms as arguments 8 8 Generic Subprogram Names Overloading 8 9 Stubs 8 10 Recursion Chapter 8 Summary Chapter 8 Exercises 86 Chapter 8 Introduction We saw in Chapter 4 that the logic of a non trivial problem could be broken down into separate subprograms or procedures each carrying out a partic
394. t of it are less than 32 while allthe valuestothe right of it are greaterthan 32 The value 32 is saidto partition the sorting problem irtotwo subproblems a left subproblem and a right supproblen These may each be sorted separately because no value in the left subproblem can ever get irtothe right subproblem and vice versa Furthermore the value 32 is inthe correct position inthe right subproblem it is the smallest value there You might think it was a lucky shot that 32 neatly partitimedthe listo start with The brilliance of the algorithm isthat given any lis we can always create a partition withthe left most value without too much difficulty Have a look now at a rearrangement of the list 32 19 41 14 28 8 72 30 87 33 L L R R The extreme ends are labelled L and R We are goingto partition the lit withthe value 32 currently at position L We define counters L and R with initial values as shown The idea now isto move L to the right while making sure that e every value to the left of position L leq partition value e andthento move R tothe left while making sure that e every value to the right of position R gt partition value Doing this gets us to this situation 32 19 41 14 28 8 72 30 87 33 L L R R What now There seems to be a deadlock But
395. t sort can only do arithmetic and display an answer Smarter ones have memory locations where intermediate results may be stored and function keys such as sin log etc The most sophisticated calculators allow you to store the sequence of operations instructions needed to calculate the solution of the problem This sequence of instructions is called a program To carry out the entire set of calculations you only need to load the program into the calculator press the run key supply the necessary data and sit back while the calculator churns out the answer A computer whether it is a small personal one like the IBM PC or a large impersonal mainframe is in principle only an advanced programmable calculator capable of storing and executing sets of instructions called programs in order to solve specific problems You may have used a computer before but only to run software packages that have been written by someone else Spreadsheets databases and word processors fall into this category If you have taken the trouble to start reading this book you probably have an interest in science or engineering and are curious enough about programming to want to write your own programs to solve your particular problems instead of relying on someone else s more general package 1 2 Fortran The particular set of rules for coding the instructions to a computer is called a programming language There are many such languages for example Fortran BASIC
396. tain a given accuracy Comparedto Newton s method 227 itis ineffi iciert Successive bisections do not necessarily move closertothe roct as usually happens with Newton s method In fact itis interesting to compare thet wo methods on the same function to see how solve the many more steps the Bisection method requiresthan Newton s method For example to 3 equation X X 3 0 the Bisection method takes 21 steps to reach the same accuracy as Newton s in five teps Passing procedures as arguments You may want to write a general purpose numerical methods module containing among other procedures a subroutine to carry out the Bisection method In that case it would be convenient to pass the function f x as an argument This can be done ifthe function is defined as an external or module functim An explicit interface is needed in this case The module NumUtils below contains a subroutine Bisect which accepts a function name Fung as adummy argument MODULE IMPLICIT NONE NumUtils CONTAINS SUBROUTINE Bisect A B E N XM Fung implements Bisection method REAL INTENT IN A B E limits and accuracy REAL INTENT OUT XM root INTEGER INTENT OUT N number of bisections REAL XL XR INTEGER I INTERFACE recommended not required FUNCTION Fung X REAL Fung
397. ter The null state may be tested for with the ASSOCIATED intrinsic function thisis useful when manipulating linked lists see below It may also be assigned to another poirter with a poirter assignment gt On the other hand if two pointers have the same target nullifying one does nct nullify the cther The ASSOCIATED intrinsic function Tf this function has one poirter argument as in ASSOCIATED P1 itretums TRUE if P1 isan alias of an object and FALSE ifitis not i e null Notethat P1 must be defined to use this function correctly ASSOCIATED may have a second argument Ifthe second argument is a target it r amp urns TRUE if the firs argument is an alias ofthe second argument Ifthe second argumert is also a poirtey it must be defined TRUE is returned if bcth poirters are null or if they are bcth aliases of the same object Arguments with the TARGET attribute Poirters associated with an actual argument that hasthe TARGET attribute do not become associated with the corresponding dummy argument but remain associated with the actual argument If a dummy argument has the TARGET attribute any poirter associated with it becomes undefined on return Dynamic variables ALLOCATE and DEALLOCATE We came across dynamic memory in Chapter 9 where we saw that storage can be allocated to an array at runtime More generally a dynamic variable
398. ter n bisectionsthe worst possible error is given by sE we wantto be surethat this is lessthan some specified error E we must seeto itthat n satisfies the la b 2 lt E r LG inequality log a b E log 2 Since n is the number of bisections it must be an integer The smallest irteger n that exceeds the right hand side of Inequality 16 2 will do as the maximum number of bisections required to guarantee the given accuracy E n gt 16 2 The following scheme may be usedto program the Bisection method It will work for any function x that changes sign in either direction between thetwo values a and b which must be found beforehand by the user The implem ion follows below 1 Reada bandE Initialize L and R 3 Compute maximum bisections n from Inequality 16 2 Repeat n times Xm Compute E N kw gt 0 then Letx Xy according to Equation 16 1 otherwise Let x Xy Prirt rot Stop We have assumed that the procedure will not with real variables are infinitesimal ind the roct exactly the chances of this happening The main advantage ofthe Bisection methodisthat itis quararteedto find a roc if you can findt wo starting values for Xi and Xr between whichthe function changes sign You can also computein advance the number of bisections needed to at
399. text file CHARACTER 1 ch INTEGER IO Num OPEN 1 FILE TEXT Io 0 Num 0 137 DO WHILE IO 1 EOF READ 1 Al IOSTAT IO ADVANCE NO IF IO 0 Num Num 1 END DO ch for encd ofvecord Non advancing T O is n available with lis directed 1 0 10 9 Miscellaneous genuine character read For completeness two furthertopics need to be mentioned here lit directed 1 0 and NAMEL List directed I O As we have seen this takes the form READ list PRINT list Under FTN90 the IOSTAT specifierreturns 1 when the encd of fileis encountered as opposedto 2 IST Data inthe input list may be separeted by commas slashes or at least one blank separators The real and imaginary parts of complex constants must be enclosed in parentheses Character constarts enclosed in delimiters apostrophes or quctes may be spread over more than one record Delimiters may be omittedifthe character constarE does not contain a blank comma or slash if it is contained within one record ifthe first characteris not a delimitey and ifthe leading characters are not numeric followed by an asterisk The reason forthe last proviso is that a data value which isto be repeated n times may be given a repeat count n E g 6 0 means the value zero isto be read six t
400. the DO loop inthe main program which isthe value it has when the second callto Fact takes place In this way Fact is never computed for an even value of I Allthisis a consequence of the variable I being global The problem is solved by redec laring I inthe functionto make it local You should make ita ruleto declare all variables used in subprograms That way you can never inadvertertly make use of a global variable inthe wrong context Tf you needto get information i rto a subprogram from its host the safest way to do itisthrough the dummy arguments When there is a large amount of such information to be shared by many is to declare global variables in a module and for subprograms subprograms the best solution needing access tothose variables to use the module see Section 8 5 The use of IMPLICIT NONE in a main program is particularly importart when there are internal subprograms It forces you to declare all local variables and dummy arguments which makes for good programming style The RETURN statement Normal exit from a subprogram occurs at its END statement However itis sometimes convenient to it from other poirts This may be done with the statement RETURN Excessive use of RI should be avoided since it very easily leads to spaghetti unstructured code Statement functions Tn alcer versions of Fortra
401. the case of the characters One way out isalwaysto use ASCII code but this may be inefficient on some computer systems A more general solution isto write a subroutine to convert lowercase alphabetic letters to uppercase based on ICHAR and CHAR which do nct rely onthe ASCII code The subroutine ToUpper inthe next program does this Ik uses ICHAR A and ICHAR a todetermine the distance bet ween the upper and lowercase letters assuming allthe letters of one caseto be contiguous i e to have consecutive codes IEthen adds this distance to allthe lowercase letters inthe word carefully avoiding uppercase letters and all nomleters To test it the program reads two words from the keyboard e g NAPOLEON and bonaparte prirtsthem in ascending order asthey are converts them both to uppercase and prints them in order again IMPLICIT NONE CHARACTER 10 Wordl Word2 143 Fl Fl AD Wordl AD Word2 IF Wordl lt Word2 THEN ELSE TU m 2 o IF PRINT Wordl Word2 RINT Word2 Wordl CALL ToUpper Wordi CALL ToUpper Word2 IF Wordl lt Word2 THEN PRINT Wordl Word2 ELSE PRINT Word2 Wordl END IF CONTAINS SUBROUTINE ToUpper String CHARACTER LEN String INTEGER I Ismall IBIG Ismall ICHAR a IBIG ICHAR A DO I 1 LEN String I
402. the integers 1 2 3 and all negative elements by zero 209 INTEGER A 4 4 V 16 F V I I 1 16 F 0 assign values to A UNPACK V A gt 0 F a Il PACK performs the reverse qoeration Further array handling irtrinsic functions are described in Appendix C 15 5 Networks In our first application of matrix multiplication we consider a problem which at first glance seems to have nothing to do with it A spy ring Suppose five spies in an espionage ring have the code names Alex Boris Cyril Denisov and Eric whom we canlabel A B C D and E respectively The hallmark of a good spy net work is that no agent is able to contact all the others The arrangement for this particular group is e Alex can cortact only Cyril e Boris can contact only Alex or Eric e Denisov can contact only Cyri e Eric can contact only Cyril ar Denisov Cyril can t contact anyone in the ring he takes information out of the ring to the spymaster Similarly Boris brings information in from the spymaster no one inthe ring can contact him The need for good spiesto know a bit of matrix theory becomes apparert when we spot that the possible paths of communication bet ween the spies can be represented by a 5 x 5 matrix withthe rows and columns representing the transmitting and receiving agents respectively thus ooooc o a al aa D am T Oo00 0
403. the nitial point after the last record the terminal point Sequential files As along the tape If the does not need As quential fil may be thought of as a continuous tape where records are located sequentially direct access record from t direct access fi file is formatted the records may be of varying length i e the record length to be specified quertial file may be read only fromthe beginning This makes the accesstime slowerthan for a file since to find something nearthe end of a sequential file you have to read every he beginning You also cannot replace or remove a record directly as you can with es However sequential files are helpful in si ions where you might needto access be atext or ASCII file We have seen the file with a word processor in this context the file would sequential files in action in reading data from disk files The following example shows how to update a sequential le Tk reads a lire of text fram the file and asks you if you want to delete the line If you don t want to deletethe line it is writ toa temporary SCRATCH created and itis cumbersome Manipulation of sequential finallythe contents of the temporary
404. the probabilities of being in these states by a six component state vector X where x 9 is the probability of him being at intersection 7 at moment The components of X f must sum to 1 since he has to be in one of these states We can express this Markov process by the following transition probability matrix P where the rows represert the next state Le comer and the columns represent the present state Home 2 ie 4 5 Bar Home 1 io esc 0 O70 2 0 0 1 3 0 Ge 30 E S H 2 0 1 3 07 60 4 0 Oy A OOo oD 51 0 0 0 2 3 Ory 2G Bar 0 0 0 D ore The entries for Home Home and Bar Bar are bcth 1 because he stays put there with certairty Using the probability matrix P we can work out his chances of being say at intersection 3 at moment t 1 as X t 1 a 3X t t 1 3X 2 To get to 3 he must have been at either 2 or 4 and his chances of moving from there are 2 3 and 1 3 respectively Mathematically this is identicaltothe Leslie matrix problem We can therefore form the new state vector from the ald one each time with a matrix equation X t 1 PX If we suppose the man starts at intersection 2 the initial probabilities willbe 0 1 0 0 0 0 The Leslie matrix program may be adapted with very few changes to generate future states PROGRAM Drunk USE MatMult IMPLICIT NONE REAL DIMENSION 6 6 P probability transitio
405. the result The reshaping is done by array element order i e SOURCE is first strung out in array element arder and then reshaped The following code H N F GER A 2 pies plein RESHAPE B 3 2 lyr Sot 4 5 6 A SHAPE 3 I Ne H wW Dp p reshapes the aray A from 208 Since an array constructor can only be used to construct a one dimensional array R ESHAP E may be usedto reshape such a constmuctorirto atwo dimensional array The following code sets up a 3 x 3 idertity matrix INTEGER DIMENSION 3 3 Idn Idn RESHAPE SOURCE 1 0 0 O 1 0 0 O 1 amp SHAPE 3 3 Note that intrinsic functions may be called with keyword actual argument using the dummy argument names as key P SHAE SIZE A DIM returnsthe size of the array A if DIM is abser words Dummy argument names are given in Appendix C E A returns a one dimensional array holding the shape of A DIM if it is presert D SOURCI m F Gy DIM NCOPI he argument DIM specifies tl This is best understood by examples which may be genereted by the following program t orthe extert along dimension ES makes NCOPII ES duplicates of SOURCE by increasing its he dimension of the result along which the duplica
406. thelements A 3 A 5 A 1 andA 2 inthat order Some of the values in the vector subscrigt may be repeated Thisis calleda many one section since morethan one element of the section is mapped orto a single array element E g AC A 3 Se Ty of is a section with both elements 2 and 4 referencing A 5 120 A many one section may not appear onthe left of an assignment statement If an array section witha vector subscript is an actual argument of a subprogram itis regarded as an expression and it may not be changed by the subprogram E may therefore not have irtent OUT or INOUT Initializing arrays with DATA All or part of an array may be initialized in a DATA statement There are a number of possibilities e g REAL DIMENSION 10 A B C 3 3 DATA A 5 0 5 1 first 5 zero last 5 one DATA B 1 5 4 0 5 2 1 section 1 5 only DATA C I J J 1 3 I 1 3 3 0 3 1 3 2 by rows Array expressions An irtrinsic operator may operate on an array as well as a scalar to produce an array expression When a unary irtrinsic operator acts on an array it acts on each element ofthe array E g X reverses the sign of each element of the array X When a binary intrinsic operation is applied to a pair of arrays of the same shape identical rank and extents the operation is applied to the corresponding elements of the operands The result
407. this way PROGRAM Testinv USE MatMult IMPLICIT NONI Gl REAL DIMENSION ALLOCATABL INTEGER I J N ira i D gt H lt x RINT Number of equations EAD N LOCATE RINT Enter coefficient matrix A by rows EAD A I J J 1 N I 1 N RINT Enter RHS vector B EAD B A N N AInv N N X N B N H Dio Do Pw D INV A x B RINT RINT Solution RINT 10F7 2 X H U uy x H ND PROGRAM TestInv You can test it on Equations 15 5 15 7 if you like withthe coefficient of x in the first equation replaced by zero This gives anon zero pivot immediately The saltion is x 1 y 1 z 3 This method which is fairly straightforward to code and very elegant is quite adequate for small systems lessthan about 20 equations Larger systems will often have many zero elements which makes the Gauss reduction inefficiert since most of the row operations will be on zeros There are more efficient procedures for such systems Chapter 15 Summary e A table or matrix may be represerted in Fortran 90 by atwo dimensional array e Statements such as DATA READ and PRINT treat the elements of multidimensional array in array element order by default i e the leftmost subscript changes most rapidly Implied DO loops
408. tion one getsthe theoretical probabilities each time this can all be done mathematically without a computer But it is interesting to confirm the limiting probabilities by simulating the drunk s progress using a random number generator see Exercise 15 3 atthe end of the charter 15 8 Solution of Linear Equations A problem that often arises in scientific applications is the solution of a system of linear equations e g 2x y Z 4 15 5 x y Z 3 15 6 3x y z 1 15 7 One method of solution is by Gauss reduction which we discuss now Gauss reduction Writethe coefficierts of the left hand side as a matrix with the right hand side constarts as a vector tothe right of the matrix separeted by a vertical line thus 2 l 1 4 1 1 1 3 3 gel L This is simply shorthand for the original s and is sometimes augmented matrix called the augmented matrix ofthe system As long as we perform only row operations onthe numbers we can omit the symbols y and z each time We will refer tothe augmented matrix as A We start withthe first row Ri and callitthe pivot row We callthe element a 2 the pivot element Divide the whole pivot row by the piv element so the augmented array now looks like this 1 1 2 1 2 2 1 1 113 3 1 l 1 217 Rows R and R are now called target rows The object isto get zeros in all the targe rows below
409. tion takes R PARAMET ER 3 R DIM NCO R A M R ALLOCAT DIM NC DIM NCOP 1 TH ES T PI DI PII OCAT SPRI R C A D I PRINT D DO D B D R B I J PII R L M I I RESET F py AB OPI IES EN M L B J R Tl ore gu m rows columns THEN rows columns IM NCOPII J 1 The one dimensional array A with elements 1 2 and 3 in this example isto be duplicated If DIM and NCOPI isl ES is 4 PRP NNN N WW WW Le 4 copies ae made along the firt dimension of B If DIM is 2 and NCOPII WNhNEFR WNhNEFR Le 2 copies are made al TRANS POS UNPACK VECTOR MASK B is tumed as ES is 2 the result is long the second dimension The source A may also be an array section E A returns tre transpose of matrix A rows transpose and columns irterchanged ET ELD returns an array with the same shape as the logical array MASK The elements of the result corresponding to true elements of MASK are assembled in array element order ECTOR A FI mthe one dimensional array VI il cther elements of the result are equal to ELD ifitis a scalar E g the following code replaces all positi Jemerts of A by
410. to left right if negative and zeros shiftedin from other end Since shifting allthe bits of an integer one positiontothe left right multiplies divides it by 2 this provides a much faster means of multiplying dividing by powers of 2 E g ISHFT 2 4 urns 16 and ISHFT 2 1 retumsl ISHFTC I SHIFT SIZE valve of I with SIZE rightmost bits shifted circularly SHIFT places to left aight ifnegative if SIZE is absert all hits are shifted NOT I logical complement of all bits in I Le all the hits of I are flipped Elemental subroutine CALL MVBITS FROM FROMPOS LEN TO TOPOS copies the sequence of bits in FROM that start amp position FROMPOS and has length LEN to TO starting at position TOPOS C 6 Vector and Matrix Multiplication Functions DOT PRODUCT VECTOR_A VECTOR_B scalar dct product for real and integer arguments Both arguments must be rank one andthe same size Ifthe arguments are logical ANY VECTOR_A AND VECTOR_B is retumed MATMUL MATRIX A MATRIX B matrix product For numeric arguments there are three possible cases arguments have been shortened to A and B e Ais nm Bis mh resutis nh e Ais m Bis hh resultis amp e Ais 4 m Bis m resultis n E g inthe first case element I J of the result is SUM MATRIX A I MATRIX B Jd Tf the arguments are l
411. tothe array Names whichis hashed into Index bythe subroutine Place andthe function Find Items supplied by the user are then searched for with Find Ifthe item is found itis displayed with its position in Names If it is not found Find returns minus the position itwould occupy in Index if itwas there Mn and Mn2 are taken as 103 and 89 respectively andthe actual hashing function used at the beginning of Find computes the sums of the squares of the ASCII codes of the characters in thr item Different hashing functions could be used depending on the nature of the lis to be searched Some experimentation might be necessary on a dummy listo find a hashing function which causes the least clumping this reduces the number of probes needed to find an item PROGRAM Hash IMPLICIT NONE INTEGER PARAMETER Mn 103 prime for hashing INTEGER PARAMETER Mn2 89 prime for double hashing INTEGER PARAMETER NameLen 20 length of names INTEGER H hash value INTEGER EOF I INTEGER N length of list should be about 0 75Mn for best results INTEGER DIMENSION Mn Index hashed list CHARACTER NameLen DIMENSION Mn Names list of names CHARACTER NameLen Item name to search for OPEN 1 FI
412. ts from the finite precision available on the computer e g two or four bytes per variable instead of an infinite number Run the following program extract X 0 1 DO XS xX F 02001 PRINT X IF X 0 2 EXIT END DO You will findthat you needto crashthe program to stop e g with etrl break on aPC X never has the value 0 2 exactly because of rounding error In fact X misses the value of 0 2 by about 10 BaS can be seen by prirting X 0 2 as well eachtime It would be better to replace the EXIT clause with TE X gt 0 2 EXIT or IF ABS X 0 2 lt 1E 6 EXIT In general itis always better to test for equality of two real expressions in this way e g IF ABS A B lt 1E 6 PRINT A practically equal to B Rounding error may be reduced although never completely eliminated by usingthe real kind with higher precision than the default eg REAL KIND 2 A B Rounding error may also be reduced by a mathematical re arrangement of the problem Ifthe well known quadratic equation is written in the less familiar fom x 2ax e 0 the two solutions may be expressed as 83 X a va e X a va e If eis very small compared with a the second roct is expressed as the difference bet ween two nearly equal numbers and considerable significance is lost E g taking a 5 x
413. ture plan of Exercise 4 2 6 13 Use the Taylor series 2 4 6 X X X 2 4 6 cosx 1 to write a program to compute cos x correctto four decimal places xis in radians See how many terms are needed to get 4figure agreement with the intrinsic function COS 6 14 A man borrows 10 000 to buy a used car Interest on his loan is compounded at the rate of 2 per month while the outstanding balance of the loan is more than 5000 and at 1 per month otherwise He pays back 300 every month except forthe last month when the repayment must be less than 300 He pays at the end of the month after the interest on the balance has been compounded The first repayment is made one month after the loan is paid out to him Write a program which writes out a monthly statement of the balance afterthe monthly payment has been made the final payment and the month of the final payment 78 6 15 A propcile the equations of motion of which are given in Chapter 3 is launched from the poirt O with an initial velocity of 60 m s at an angle of 50 tothe horizontal Write a program which computes and writes out the time inthe air and horizontal and vertical displacement from the point O every 0 5 seconds as long as the projectile remains above a horizontal plane through O 6 16 When a resistor R capacitor C and battery V are connected in series a charge Q
414. ty matrix In general the reachability matrix R of a n x n network may be defined asthe sum ofthe first n 1 powers of its associated adjacency matrix A You may be wondering why we can stop at the n n 1 1 th power of A The elements of A will be the number of paths that have n 1 arcs i e that connect n nodes since each arc connects two nodes Since there are no further nodes that can be reached it is not necessary to raise A tothenth power The subroutine Reachable in the program below computes the reachability matrix R for any net work given the adjacency matrix A i e it computes 2 3 1 R AtA 4 At Al Pe er n x n Ik uses the array B to stare the irtemediat powers of the array A adding them to R each time The complete program to compute a reachability matrix follows It uses the module MatMult defined in Section 15 3 PROGRAM Reach USE MatMult IMPLICIT NONE REAL DIMENSION ALLOCATABL INTEGER I J N GI A R use dynamic arrays PRINT Number of nodes in network READ N ALLOCATE A N N R N N P RI PE RINT Enter Adjacency matrix by rows EAD A I J J 1 N I 1 N CALL Reachable A R PRINT Reachability matrix PRINT DO I 1 N PRINT 20F3 0 R I J J 1 N END DO CONTAINS SUBROUTINE Reachable A R 212
415. ubprograms e a module may contain declaretion and speci program units which use the module Modules are also compiled separately Ju main program The amended main program is US Fl MyUtils DH Ei D td MPLICIT NON LA B Gl A eal D D A Pi L SWOP A B RINT A B vow D pa m ND whilethe module again saved in a separate file is MODULE MyUtils REAL PARAMETER Pi 3 1415927 CONTAINS SUBROUTINE SWOP X Y REAL Temp X Y Temp X X Y Y Temp END SUBROUTINE SWOP D MODULE MyUtils m 2 The general form of a module is MODULE name declaration statements CONTAINS fication statements which are accessible to all Inthe following example the subroutine SWOP is placed ina module MyUtils For the sake of lustretion the module also declares a real parameter Pi The main program now has a statement USE MyUtils which rendersthe module accessibleto it The name Pi istherefore known tothe Note that the EXTERNAL statement is now neither necesssary nor in fact correct since SWOP is no longer an extemal subprogram it is now technically a module subprogram 95 module subprograms END MODULE name Tt is accessed by means of a USE statement in the host program unit which must precede all her statements USE module nam
416. ular well defined task It often happens that such subprograms can be used by many different main programs and in fact by different users of the same computer system Fortran 90 enables you to implement these subprograms as functions and subroutines which are independent of the main program Examples are procedures to perform statistical operations or to sort items or to find the best straight line through a set of points or to solve a system of differential equations Subprograms may be internal or external Useful procedures may be collected together as libraries Such collections are called modules Main programs i e everything we have seen so far external subprograms and modules are referred to as program units Basically an internal subprogram is contained within another program unit and therefore compiled with it whereas an external subprogram is not it is in fact compiled separately An important difference between the two types of subprogram is that an_ internal subprogram may use names of entities declared by the program unit that contains it whereas an external subprogram is not contained within another program unit We deal first with internal subprograms 8 1 Internal Subprograms There are two types of subprograms functions and subroutines We will first look at functions We have already seen how to use some of the intrinsic functions supplied by Fortran 90 such as SIN COS LOG amp c You can
417. ular hashed position might be found to be occupied already the elements of Index should be initializedto some negative value say 100 to indicate that they are all unoccupied at first This is called a collision There are various ways of dealing with collisions One isto use the next position but this causes clumping of the hashed lig which is inefficient A more imaginative solution to the problem of collisions is to use double hashing At this stage we need a little more notation Let s rather call the original hash value H For best results the length of the Index array needsto be a prime number Let s call it Mn So K isin fact given by K MOD H Mn 1 167 For double hashing choose ancther prime Mn2 which is slightly lessthan Mn If position K is occupied look in position K InK where InK MOD H Mn2 Continue increasing K like this modulo Mn until an unoccupied position is found When we have finished we wilLhave a hashed lit in Index To finda particular item hash it and orobe ac K K Ink until either an unoccupied position not found ara match is found For the best results the tctal number of items in Names should n exceed 0 75Mn The program Hash below demonstrates hashing on a lit of names in the sequential file NAMES which is set up separately The fileis readin
418. ure 15 1 Figure 15 1 Cost table Di D2 D3 Si 3 12 10 82 17 18 35 S31 7 10 24 The factories can supply 4 12 and 8 loads per day respectively and the sites require 10 9 and 5 loads per day respectively The real problem isto findthe cheapest way to satisfythe demands at the sites but we are not considering that here Suppose the factory manager proposes the following transportation scheme each entry represents the number of loads of concrete to be transported along that particular route Di D2 D3 Si 4 0 O ETA E e Gs 20 sol Old 5 This sort of scheme is called a solution to the transportation problem The cost table and the solution can then be represented by tables C and X say where Cli isthe entry in row and column j of the cost table with a similar convention for X To computethe cost of the above solution each entry inthe solutiontable must be multiplied by the corresponding ertry inthe costtable This operation is not to be confused with matrix multiplication which is discussed below We therefore want to calculate 3x4 12x0 4 24x5 The following program will cb what is required INTEGER DIMENSION 3 3 C X DATA C L J J 1 3 I 1 3 amp Be TO Ly ET Eer BS Ty CLO 2AE DATAS CCX T Uy SH Ly Sy B aay Sy fA Og 07 65 Oy O55 O By OAL TotCost 0 DO I 1 3 DO J 1 3 TotCost TotCost C I J X I J END DO END D
419. ut S13 5 ELEMENTS 1 S23 4 ELEMENTS 2 S1 S2 2 ELEMENTS 2 There are a numb e The PRIVATE statemert makes the components of the derived SI the module T code that uses it e The function Card allows the cardinality of a set to be accessible outside the module e TOQ LEMENTS LEMENTS LEMENTS operator works The only novelty is being able to replace the conventional statement r of very Important poirts to ncte fine a binary operator on a derivedtype a function must be q ET type inaccessible outside Fined that speci his means itis possibleto change thetype definition without havingto change any fies how the S3 Intersect S1 S2 with the much more natural syntax S3 SL 2 This is achieved by ass using the keyword OPERATOR INTERFAC T OP ERATOR MODULE PROCEDURE END INTERFACE F Intersect ing the function name with the operator token in an irterface block A function defining a unary operator would obviously have only one argument e Thed fined operetartoken Le a sequence of characters may be any one ofthetokens used for the intrinsic operators or a sequence of up to 31 letters enclosed in decimal poirts such as IN above
420. ve the block is executed with J starting at J and increased by L everytime until it has been executed forthe greatest value of Inot exceeding K e TfL gt 0andJ gt K the block is na executed at all zero trip court e IfLis negative the block is executed with I starting at J and decreased by L everytime untilit has been executed forthe smallest value of Jnot less than K e TfL lt OandJ lt K the block is na executed at all zero trip court Fig 6 1 DO Parameters The formula forthe iteration count is evaluated before the block is executed forthe first time Even ifthe values ofthe DO parameters are subsequently changed insice the block this will not affect the atteration count These rules are summarized in Figure 6 1 The DO variable and parameters may be real This feature however has been declared obsolescent Le may be removed entirely from the next standard so you shouldtry very hard not to use itif you are an ald Fortran addict E gives rise to all sorts of nasty rounding errors 6 3 DO with Non integer Increments There are many situations in sciertific and engineering computing when one warts to make nom irteger incremerts in a loop Consider again the stone thrown vertically upwards in Chapter 2 Suppose it is launched at time t 0 seconds and we want to compute its position s between anes 7 fo ang T
421. w POINT Next lt A variable of this type is usually represerted as follows the top box being for the value and the bottom one for the poirterto the next node We will clae two variables of this type TYPE NODE POINTER Current L Current isthe name of a general node while L marksthe end of the list Thet wo most important things about a linked list are where it starts and where it ends We could have a separate pointerto mark the beginning of the lig but this can also be done with a null pointer since this can be tested for Inthially the list will be empty so L should point to both the beginning and the end This is effected by initially nullifying L NULLIFY L The null poirter is usually reoreserted by the symbol for earthing an electrical conductor Let s now set up a list with one node containing the integer value Num Firstly dynamic storage must be allocated for Current ALLOCATE Current Next give it avalue that s easy Current Value Num Finally andthisisthe only really tricky part we must arrange for L to poirt tothe end of the list Where isthat Wel the last and only node addedis Current so L must poirtto be an alias of Current L gt Current Ifthe value of Num is 1 the si ion now looks like this L bj This process can be repeated as long as you l
422. when sorted Num SIZE X m 2 116 Gl Sorted FALSE initially unsorted K 0 count the passes DO WHILE NOT Sorted Sorted TRUE they could be sorted K K 41 another pass DO J 1 Num K fewer tests on each pass IF X J gt X J 1 THEN are they in order Temp X J no X J X J 1 X J 1 Temp Sorted FALSE a swop was made END IF END DO END DO ND SUBROUTINE 0 Fl Bubble Sort is written here as an intemal subroutine but will run as it stands as an external subroutine or in a module eject 9 7 Sorting a List Quick Sort Try sorting 1000 numbers withthe Bubble Sort Tt takes quite a while Sorting 10 000 numbers a not inconceivable problem wouldtake about 100 times longer The famous Quick Sort algorithm invented by C A R Hoarein 1960 is much faster Itis based on the divide and conquer approach to solve a big problem break it down irto smaller subproblems and break each subproblem down inthe same way untilthey are small enough to solve As someone has remarked Every problem has a smaller problem insi waiting to get ouw How do we break our sorting problem down into manageable subproblems Well have a look atthe following lis Number 19 30 14 28 8 32 72 41 87 33 Postion 1 2 3 4 5 6 7 8 9 10 The value 32 in position 6 has a special property All the values to the lef
423. written under earlier versions The implicit type rule can lead to serious programming errors A real value might unwittingly be assigned to a variable which is irteger by default the fractional part isthen truncated chopped off For example the statement Interest rate 0 12 ina program where Interest rete is nt declared explicitly will assign the value 0 to the variable To guard against such errors it is strongly recommended that the tatement IMPLICIT NONI Gl be used at the start of all programs This statement switches offthe implicittype rule consequently all variables used inthe program must be declared This incidentally promotes good programming style having to declare a variable means that you have been forced to think about what it reoreserts 2 6 Vertical Motion under Gravity Ifa stone isthrown vertically upward with an initial speed u its vertical displacement s afteratime t 3 has elapsed is given by the formula S x TA where g is the acceleration due to gravity Air resistance has been ignored We would liketo compute the value of s given u and t Note that we are not concemed here with how to derive the formula but how to compute its value The logical preparation of this program is as follows 14 1 Get values of g u and tirto the computer 2 Compute the value of s according to th fomula
424. xact solution 7 The left hand side of Equation 16 17 is usually approximated by a forward difference COU 2 U jy U j a k One way of approximating the right hand side of Equation 16 17 is as follows 2 OU _ Wij 2u FU 2 2 x h 16 18 This leads to ascheme which although easy to compute isonly conditionally stable Tf however we replace the right hand side ofthe scheme in Equation 16 18 by the mean ofthe finit difference approximation onthe jth and j 1 thtime rows we getthe following scheme for Equation 16 17 TU j 2 2r U1 U j Fy ay 2 2r u 7U 1 EE 2 where F k h This is known as the Crank Nicolson implicit method since it involves the solution of a system of simultaneous equations as we shall see To illustrete the method numerically let s suppose that the rod has a length of 1 unit and that its ends are in contact with blocks of ice i e the boundary conditions are U 0 ft U 1 0 Suppose also that the initial temperature is given by the initial condition 2x 0 lt x lt 1 2 2 1 x 1 2 lt x lt 1 U x 0 This situation could come about by heating the centre of the rod for a longtime withthe ends kept incontact withthe ice removingthe heat source atime 0 This particular problem has symmetry abou the line x 1 2 we exploit this fact in finding the solution If we take h
425. y Af x n 16 9 defining Y as VX where 1 nh and where Yo y 0 Bacteria growth Euler s method Euler s method performs quite adequately in the skydiver problem once we have got the right value of the step length h In case you think that the numerical solution of all differential equations is just as easy we will now consider an example where Euler s method doesn t do too well Suppose a colony of 1000 bacteria are multiplying at the rate of r 0 8 per hour per individual i e an individual produces an average of 0 8 offspring every hour How many bacteria are there after 10 hours Assuming that the colony grows continuously and without restriction we can model this growth with the differential equation dNidt rN N 0 1000 16 10 where N t is the population size at time t This process is called exponential growth Equation 16 10 may be exponential growth solved analytically to give the well known formula for exponential growth N t N O e To solve Equation 16 10 numerically we apply Euler s algorithm to it to get Nu Ni rhN 46 11 where N N t and Ny 1000 Taking h 0 5 gives the results shown in Table 16 1 where the exact solution is also given This time the numerical solution in the column headed Euler is not too good In fact the error gets worse at each step and after 10 hours of bacteria time it is about 72 Of course the numerical solution will improve if we take h smalle
426. y are available throughout the scope of the host program This scope includes all intemal subprograms This can sometimes lead to serious bugs which is why internal subprograms should only be used for fairly small tasks peculiarto their particular host More general procedures should be written as external subprograms Since an intemal subprogram is in a sense declared in its host this scoping rule also implies that irternal subprograms are known to each her Le they may call each her However if a variable is redeclared in a subprogram that subprogram no longer has access to the original variable of the same name declared in the host Arguments The arguments in a subprogram statement eg X Y and Ain FUNCTION YNew X Y A are dummy arguments That is they exist only for the purpose of defining the function They represerrk general variables of the same type Consequently the same names do not have to be used when calling or invoking the subprogram E g YNew may be invoked in the host program withthe statement YNew U V Pi 2 You can think of the values of the actual arguments U V and Pi 2 being copied intothe dummy arguments X Y and A respectively The actual arguments are saidto be passed to the subprogram An actual argument which is a variable name must have the same type and kindtype parameters as its corresponding dummy argument The exact wa
427. y as follows V SQRT U COS A 2 U SIN A g T 2 The argument of SORT is always positive here why so no problems can arise Angles for the trigonometric functions must be expressed in radians and are returned in radians where appropriate To convert degreesto radians multiplythe angle in degrees by 7 180 where n is the well known transcendental number 3 1415926 If you want to impress your friends however you can cunningly exploit the mathematical fact that the arc tangent inverse tangent of 1 is 7 4 and use the ATAN function try it Some useful intrinsic functions 35 Descrictions of all the intrinsic procedures supported by Fortran 90 appearin Appendix C A list of some of the more common ones follows X stands for a real expression unless otherwise stated Optional arguments are indicated in square brackets ABS X ABS absolute value of irteger real ar complex X ACOS X ACOS arc cosine inverse cosine of X ASIN X ASIN arc sire of X ATAN X ATAN arc tangert of X inthe range 1 2 to 7 2 ATAN2 Y X ATAN2 ar tangert of y x inthe range n to 7 COS X COS cosine of real or complex X COSH X COSH hyperbolic cosine of X COT X COT cctangert of X EXP X EXP value ofthe exponential function ey where X may be real or complex INT X KIND INT convertsirteger real or complex X to integertype truncating toward
428. y in which arguments are passed is discussed below You should be aware that if the value of a dummy argument is changed inside a function that change is copied back into the corresponding actual argument in the host program if it is a variable This is an undesirable side effect ina function and should be avoided in the interests of sound programming If you want to change an actual argument the correct vehicle is a subroutine 89 Local and global vari ables The next program contains an internal function Fact N which computes n There is something wrong with it See if you can work out by hand what the first few lines of output will be before running it PROGRAM Factorial IMPLICIT NONE INTEGER I DO I 1 10 PRINT I Fact I END DO CONTAINS FUNCTION Fact N Temp 1 DO I 2 N Temp I Temp END DO Fact Temp END FUNCTION ig Z OF INTEGER Fact N Temp The problem isthat I isa global variable ie the name I represents the same variable inside and outside the function Fact is first called when I 1 which isthe first value written This value is passed tothe function s dummy argument N The same I is now given the initial value 2 by the DO loop inside Fact but since itis greaterthan N the DO loop is ng executed so I stillhasthe value 2 when Fact retumsto be printed inthe main program However I is now incremented to 3 in
429. y to store the primes as they are found Tn an experiment N pairs of observations X Y are made The best straight lineleast squares that may be drawn through these poirts usingthe method of Least Squares has intercept A onthe x axis and slope B where B S S S N S S2 N A S N S B N and S x S X S gt S xX The correlation coefficient R is given by E NS S 8 JNS S2 JNS S2 where S sum Y R 1 implies a perfect linear relationship between X and Y This fact can be used to test your program All the summations are overthe range 1 to N The observations are stored in atext file tis not known how many observations there are Write a program to read the data and compute B and R Hint you don t need arrays Ifa set of points X Y are joined by straight lines the value of Y correspondingto a value X which lies on a straight line bet ween X and_X is given by Yun IT Xie X Y Y X X This process is called linear interpolation Suppose nolinear interoolationinterpolation more than 100 sets of data pairs are stored in ascending order of X in a text file Write a program which will compute an interpolated value of Y given an arbitrary value of X keyed in at the keyboard It is assumed that X is inthe range covered by the data Note that the data must be sorted into ascending order with respect tothe X va
Download Pdf Manuals
Related Search
Related Contents
steaming hot water tap SurveyMonkey User Manual LOEWE BluTech Vision Interactive 9R122-A M203 Manual - Meriam Process Technologies Altronix MAXIMAL5D power distribution unit PDU veladura al agua sombra 911 descripcion ART EASYTRIM アクティブトラッカー 取扱説明書 Sonic Alert The Skull Alarm Clock with Bone Crusher and MP3 Input Reloop IQ2 MIDI Copyright © All rights reserved.
Failed to retrieve file