572
Sample page from NUMERICAL RECIPES IN FORTRAN 90: The Art of PARALLEL Scientific Computing (ISBN 0-521-57439-0) Copyright (C) 1986-1996 by Cambridge University Press. Programs Copyright (C) 1986-1996 by Numerical Recipes Software. Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copying of machine- readable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books, diskettes, or CDROMs visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to [email protected] (outside North America). Numerical Recipes in Fortran 90 Second Edition Volume 2 of Fortran Numerical Recipes

Numerical Recipes in FORTRAN 90 - CPIS Vietnamdanida.vnu.edu.vn/cpis/files/Books/NumericalRecipesinF90.pdf · Sample page from NUMERICAL RECIPES IN FORTRAN 90: ... 2. Parallel programming

  • Upload
    vanthu

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Numerical Recipesin Fortran 90

    Second Edition

    Volume 2 ofFortran Numerical Recipes

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Numerical Recipesin Fortran 90

    The Art of Parallel Scientific ComputingSecond Edition

    Volume 2 ofFortran Numerical Recipes

    William H. PressHarvard-Smithsonian Center for Astrophysics

    Saul A. TeukolskyDepartment of Physics, Cornell University

    William T. VetterlingPolaroid Corporation

    Brian P. FlanneryEXXON Research and Engineering Company

    Foreword by

    Michael MetcalfCERN, Geneva, Switzerland

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Published by the Press Syndicate of the University of CambridgeThe Pitt Building, Trumpington Street, Cambridge CB2 1RP40 West 20th Street, New York, NY 10011-4211, USA10 Stamford Road, Oakleigh, Melbourne 3166, Australia

    Copyright c Cambridge University Press 1986, 1996,except for all computer programs and procedures, which areCopyright c Numerical Recipes Software 1986, 1996,and except for Appendix C1, which is placed into the public domain.All Rights Reserved.

    Numerical Recipes in Fortran 90: The Art of Parallel Scientific Computing,Volume 2 of Fortran Numerical Recipes, Second Edition, first published 1996.Reprinted with corrections 1997.The code in this volume is corrected to software version 2.08

    Printed in the United States of AmericaTypeset in TEX

    Without an additional license to use the contained software, this book is intended asa text and reference book, for reading purposes only. A free license for limited use of thesoftware by the individual owner of a copy of this bookwho personally types one or moreroutines into a single computer is granted under terms described on p. xviii. See the sectionLicense Information (pp. xviixx) for information on obtaining more general licenses atlow cost.

    Machine-readablemedia containing the software in this book, with included licensesfor use on a single screen, are available from Cambridge University Press. See theorder form at the back of the book, email to [email protected] (North America) [email protected] (rest of world), or write to Cambridge University Press, 110Midland Avenue, Port Chester, NY 10573 (USA), for further information.

    The software may also be downloaded, with immediate purchase of a licensealso possible, from the Numerical Recipes Software Web site (http://www.nr.com).Unlicensed transfer of Numerical Recipes programs to any other format, or to anycomputer except one that is specifically licensed, is strictly prohibited. Technical questions,corrections, and requests for information should be addressed to Numerical RecipesSoftware, P.O. Box 243, Cambridge, MA 02238 (USA), email [email protected], or fax781 863-1739.

    Library of Congress Cataloging-in-Publication DataNumerical recipes in Fortran 90 : the art of parallel scientific computing / William H. Press. . . [et al.]. 2nd ed.

    p. cm.Includes bibliographical references and index.ISBN 0-521-57439-0 (hardcover)1. FORTRAN 90 (Computer program language) 2. Parallel programming (Computerscience) 3. Numerical analysisData processing.

    I. Press, William H.QA76.73.F25N85 1996519.4028552dc20 96-5567

    CIP

    A catalog record for this book is available from the British Library.

    ISBN 0 521 57439 0 Volume 2 (this book)ISBN 0 521 43064 X Volume 1ISBN 0 521 43721 0 Example book in FORTRANISBN 0 521 57440 4 FORTRAN diskette (IBM 3.5 )ISBN 0 521 57608 3 CDROM (IBM PC/Macintosh)ISBN 0 521 57607 5 CDROM (UNIX)

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Contents

    Preface to Volume 2 viii

    Foreword by Michael Metcalf x

    License Information xvii

    21 Introduction to Fortran 90 Language Features 93521.0 Introduction 93521.1 Quick Start: Using the Fortran 90 Numerical Recipes Routines 93621.2 Fortran 90 Language Concepts 93721.3 More on Arrays and Array Sections 94121.4 Fortran 90 Intrinsic Procedures 94521.5 Advanced Fortran 90 Topics 95321.6 And Coming Soon: Fortran 95 959

    22 Introduction to Parallel Programming 96222.0 Why Think Parallel? 96222.1 Fortran 90 Data Parallelism: Arrays and Intrinsics 96422.2 Linear Recurrence and Related Calculations 97122.3 Parallel Synthetic Division and Related Algorithms 97722.4 Fast Fourier Transforms 98122.5 Missing Language Features 983

    23 Numerical Recipes Utility Functions for Fortran 90 98723.0 Introduction and Summary Listing 98723.1 Routines That Move Data 99023.2 Routines Returning a Location 99223.3 Argument Checking and Error Handling 99423.4 Routines for Polynomials and Recurrences 99623.5 Routines for Outer Operations on Vectors 100023.6 Routines for Scatter with Combine 100223.7 Routines for Skew Operations on Matrices 100423.8 Other Routines 1007

    Fortran 90 Code Chapters 1009

    B1 Preliminaries 1010B2 Solution of Linear Algebraic Equations 1014B3 Interpolation and Extrapolation 1043

    v

  • vi ContentsSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).B4 Integration of Functions 1052B5 Evaluation of Functions 1070B6 Special Functions 1083B7 Random Numbers 1141B8 Sorting 1167B9 Root Finding and Nonlinear Sets of Equations 1182B10 Minimization or Maximization of Functions 1201B11 Eigensystems 1225B12 Fast Fourier Transform 1235B13 Fourier and Spectral Applications 1253B14 Statistical Description of Data 1269B15 Modeling of Data 1285B16 Integration of Ordinary Differential Equations 1297B17 Two Point Boundary Value Problems 1314B18 Integral Equations and Inverse Theory 1325B19 Partial Differential Equations 1332B20 Less-Numerical Algorithms 1343

    References 1359

    Appendices

    C1 Listing of Utility Modules (nrtype and nrutil) 1361C2 Alphabetical Listing of Explicit Interfaces 1384C3 Index of Programs and Dependencies 1434

    General Index to Volumes 1 and 2 1447

  • Contents viiSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).Contents of Volume 1: Numerical Recipes in Fortran 77

    Plan of the Two-Volume Edition xiiiPreface to the Second Edition xvPreface to the First Edition xviiiLicense Information xxComputer Programs by Chapter and Section xxiv

    1 Preliminaries 12 Solution of Linear Algebraic Equations 223 Interpolation and Extrapolation 994 Integration of Functions 1235 Evaluation of Functions 1596 Special Functions 2057 Random Numbers 2668 Sorting 3209 Root Finding and Nonlinear Sets of Equations 340

    10 Minimization or Maximization of Functions 38711 Eigensystems 44912 Fast Fourier Transform 49013 Fourier and Spectral Applications 53014 Statistical Description of Data 60315 Modeling of Data 65016 Integration of Ordinary Differential Equations 70117 Two Point Boundary Value Problems 74518 Integral Equations and Inverse Theory 77919 Partial Differential Equations 81820 Less-Numerical Algorithms 881

    References 916Index of Programs and Dependencies 921

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Preface to Volume 2Fortran 90 is not just the long-awaited updating of the Fortran language to

    modern computing practices. It is also the vanguard of a much larger revolution incomputing, that of multiprocessor computers and widespread parallel programming.Parallel computing has been a feature of the largest supercomputers for quite sometime. Now, however, it is rapidly moving towards the desktop.

    As we watched the gestation and birth of Fortran 90 by its governing X3J3Committee (a process interestingly described by a leading committee member,Michael Metcalf, in the Foreword that follows), it became clear to us that the rightmoment for moving Numerical Recipes from Fortran 77 to Fortran 90 was sooner,rather than later.

    Fortran 90 compilers are now widely available. Microsofts Fortran PowerSta-tion for Windows 95 brings that firms undeniable marketing force to PC desktop;we have tested this compiler thoroughly on our code and found it excellent incompatibility and performance. In the UNIX world, we have similarly tested, andhad generally fine experiences with, DECs Fortran 90 for Alpha AXP and IBMs xlffor RS/6000 and similar machines. NAGs Fortran 90 compiler also brings excellentFortran 90 compatibility to a variety of UNIX platforms. There are no doubtother excellent compilers, both available and on the way. Fortran 90 is completelybackwards compatible with Fortran 77, by the way, so you dont have to throw awayyour legacy code, or keep an old compiler around.

    There have been previous special versions of Fortran for parallel supercomput-ers, but always specific to a particular hardware. Fortran 90, by contrast, is designedto provide a general, architecture-independent framework for parallel computation.Equally importantly, it is an international standard, agreed upon by a large group ofcomputer hardware and software manufacturers and international standards bodies.

    With the Fortran 90 language as a tool, we want this volume to be your completeguide for learning how to think parallel. The language itself is very general inthis regard, and applicable to many present and future computers, or even to otherparallel computing languages as they come along. Our treatment emphasizes general

    principles, but we are also not shy about pointing out parallelizationtricks that have frequent applicability. These are not only discussedin this volumes principal text chapters (Chapters 2123), but are also

    sprinkled throughout the chapters of Fortran 90 code, called out by a special parallel

    f90hint logo (left, above). Also scattered throughout the code chaptersare specific Fortran 90 tips, with their own distinct graphic call-out(left). After you read the text chapters, you might want simply to browse

    among these hints and tips.A special note to C programmers: Right now, there is no effort at producing a

    parallel version of C that is comparable to Fortran 90 in maturity, acceptance, andstability. We think, therefore, that C programmers will be well served by usingthis volume for an educational excursion into Fortran 90, its parallel programmingconstructions, and the numerical algorithms that capitalize on them. C and C++programming have not been far from our minds as we have written this volume,and we think that you will find that time spent in absorbing its principal lessons(in Chapters 2123) will be amply repaid in the future, as C and C++ eventuallydevelop standard parallel extensions.

    viii

  • Preface to Volume 2 ixSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).A final word of truth in packaging: Dont buy this volume unless you also

    buy (or already have) Volume 1 (now retitled Numerical Recipes in Fortran 77).Volume 2 does not repeat any of the discussion of what individual programs actuallydo, or of the mathematical methods they utilize, or how to use them. While ourFortran 90 code is thoroughly commented, and includes a header comment foreach routine that describes its input and output quantities, these comments are notsupposed to be a complete description of the programs; the complete descriptionsare in Volume 1, which we reference frequently. But heres a money-saving hintto our previous readers: If you already own a Second Edition version whose titleis Numerical Recipes in FORTRAN (which doesnt indicate either Volume 1 orVolume 2 on its title page) then take a marking pen and write in the words Volume1. There! (Differences between the previous reprintings and the newest reprinting,the one labeled Volume 1, are minor.)

    Acknowledgments

    We continue to be in the debt of many colleagues who give us the benefit oftheir numerical and computational experience. Many, though not all, of these arelisted by name in the preface to the second edition, in Volume 1. To that list we mustnow certainly add George Marsaglia, whose ideas have greatly influenced our newdiscussion of random numbers in this volume (Chapter B7).

    With this volume, we must acknowledge our additional gratitude and debt to anumber of people who generously provided advice, expertise, and time (a great dealof time, in some cases) in the areas of parallel programming and Fortran 90. Theoriginal inspiration for this volume came fromMike Metcalf, whose clear lectures onFortran 90 (in this case, overlooking the beautiful Adriatic at Trieste) convinced usthat Fortran 90 could serve as the vehicle for a book with the larger scope of parallelprogramming generally, and whose continuing advice throughout the project hasbeen indispensable. Gyan Bhanot also played a vital early role in the developmentof this book; his first translations of our Fortran 77 programs taught us a lot aboutparallel programming. We are also grateful to Greg Lindhorst, Charles Van Loan,Amos Yahil, Keith Kimball, Malcolm Cohen, Barry Caplin, Loren Meissner, MitsuSakamoto, and George Schnurer for helpful correspondence and/or discussion ofFortran 90s subtler aspects.

    We once again express in the strongest terms our gratitude to programmingconsultant Seth Finkelstein, whose contribution to both the coding and the thoroughtesting of all the routines in this book (against multiple compilers and in sometimes-buggy, and always challenging, early versions) cannot be overstated.

    WHP and SAT acknowledge the continued support of the U.S. National ScienceFoundation for their research on computational methods.

    February 1996 William H. PressSaul A. Teukolsky

    William T. VetterlingBrian P. Flannery

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Forewordby Michael Metcalf

    Sipping coffee on a sunbaked terrace can be surprisingly productive. One ofthe Numerical Recipes authors and I were each lecturing at the International Centerfor Theoretical Physics in Trieste, Italy, he on numerical analysis and I on Fortran90. The numerical analysis community had made important contributions to thedevelopment of the new Fortran standard, and so, unsurprisingly, it became quicklyapparent that the algorithms for which Numerical Recipes had become renownedcould, to great advantage, be recast in a new mold. These algorithms had, hitherto,been expressed in serial form, first in Fortran 77 and then in C, Pascal, and Basic.Now, nested iterations could be replaced by array operations and assignments, andthe other features of a rich array language could be exploited. Thus was the idea of aNumerical Recipes in Fortran 90" first conceived and, after three years gestation,it is a delight to assist at the birth.

    But what is Fortran 90? How did it begin, what shaped it, and how, after nearlyfoundering, did its driving forces finally steer it to a successful conclusion?

    The Birth of a Standard

    Back in 1966, the version of Fortran now known as Fortran 66 was the firstlanguage ever to be standardized, by the predecessor of the present AmericanNationalStandards Institute (ANSI). It was an all-American affair. Fortran had first beendeveloped by John Backus of IBM in New York, and it was the dominant scientificprogramming language in North America. Many Europeans preferred Algol (inwhich Backus had also had a hand). Eventually, however, the mathematicians whofavored Algol for its precisely expressible syntax began to defer to the scientists andengineers who appreciated Fortrans pragmatic, even natural, style. In 1978, theupgraded Fortran 77 was standardized by the ANSI technical committee, X3J3, andsubsequently endorsed by other national bodies and by ISO in Geneva, Switzerland.Its dominance in all fields of scientific and numerical computing grew as new, highlyoptimizing compilers came onto the market. Although newer languages, particularlyPascal, Basic, PL/1, and later Ada attracted their own adherents, scientific usersthroughout the 1980s remained true to Fortran. Only towards the end of that decadedid C draw increasing support from scientific programmers who had discovered thepower of structures and pointers.

    During all this time, X3J3 kept functioning, developing the successor versionto Fortran 77. It was to be a decade of strife and contention. The early plans, in thelate 1970s, were mainly to add to Fortran 77 features that had had to be left out ofthat standard. Among these were dynamic storage and an array language, enablingit to map directly onto the architecture of supercomputers, then coming onto themarket. The intention was to have this new version ready within five years, in 1982.But two new factors became significant at that time. The first was the decision thatthe next standard should not just codify existing practice, as had largely been thecase in 1966 and 1978, but also extend the functionality of the language through

    x

  • Foreword xiSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).innovative additions (even though, for the array language, there was significantborrowing from John Iversons APL and from DAP Fortran). The second factor wasthat X3J3 no longer operated under only American auspices. In the course of the1980s, the standardization of programming languages came increasingly under theauthority of the international body, ISO. Initially this was in an advisory role, butnow ISO is the body that, through its technical committee WG5 (in full, ISO/IECJTC1/SC22/WG5), is responsible for determining the course of the language. WG5also steers the work of the development body, then as now, the highly skilled andcompetent X3J3. As we shall see, this shift in authority was crucial at the mostdifficult moment of Fortran 90s development.

    The internationalization of the standards effort was reflected in the welcomegiven by X3J3 to six or seven European members; they, and about one-third ofX3J3s U.S. members, provided the overlapping core of membership of X3J3 andWG5 that was vital in the final years in bringing the work to a successful conclusion.X3J3 membership, which peaked at about 45, is restricted to one voting memberper organization, and significant decisions require a majority of two-thirds of thosevoting. Nationality plays no role, except in determining the U.S. position on aninternational issue. Members, who are drawn mainly from the vendors, largeresearch laboratories, and academia, must be present or represented at two-thirds ofall meetings in order to retain voting rights.

    In 1980, X3J3 reported on its plans to the forerunner of WG5 in Amsterdam,Holland. Fortran 8x, as it was dubbed, was to have a basic array language, newlooping constructs, a bit data type, data structures, a free source form, a mechanismto group procedures, and another to manage the global name space. Old features,including COMMON, EQUIVALENCE, and the arithmetic-IF, were to be consigned to aso-called obsolete module, destined to disappear in a subsequent revision. This waspart of the core plus modules architecture, for adding new features and retiringold ones, an aid to backwards compatibility. Even though Fortran 77 compilerswere barely available, the work seemed well advanced and the mood was optimistic.Publication was intended to take place in 1985. It was not to be.

    One problem was the sheer number of new features that were proposed asadditions to the language, most of them worthwhile in themselves but with thetotality being too large. This became a recurrent theme throughout the developmentof the standard. One example was the suggestion of Lawrie Schonfelder (LiverpoolUniversity), at a WG5 meeting in Vienna, Austria, in 1982, that certain featuresalready proposed as additions could be combined to provide a full-blown deriveddata type facility, thus providingFortranwith abstract data types. This ideawas takenup by X3J3 and has since come to be recognized, along with the array language, asone of the two main advances brought about by what became Fortran 90. However,the ramifications go very deep: all the technical details of how to handle arrays ofobjects of derived types that in turn have array components that have the pointerattribute, and so forth, have to be precisely defined and rigorously specified.

    Conflict

    The meetings of X3J3 were often full of drama. Most compiler vendors wererepresented as a matter of course but, for many, their main objective appeared tobe to maintain the status quo and to ensure that Fortran 90 never saw the light of

  • xii ForewordSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).day. One vendors extended (and much-copied) version of Fortran 77 had virtuallybecome an industry standard, and it saw as its mission the maintenance of this lead.A new standard would cost it its perceived precious advantage. Other large vendorshad similar points of view, although those marketing supercomputers were clearlykeen on the array language. Most users, on the other hand, were hardly prepared toinvest large amounts of their employers and their own resources in simply settlingfor a trivial set of improvements to the existing standard. However, as long asX3J3 worked under a simple-majority voting rule, at least some apparent progresscould be made, although the underlying differences often surfaced. These were evensometimes between users those who wanted Fortran to become a truly modernlanguage and those wanting to maintain indefinite backwards compatibility for theirbillions of lines of existing code.

    At a watershed meeting, in Scranton, Pennsylvania, in 1986, held in anatmosphere that sometimes verged on despair, a fragile compromise was reachedas a basis for further work. One breakthrough was to weaken the procedures forremoving outdated features from the language, particularly by removing no featureswhatsoever from the next standard and by striking storage association (i.e., COMMONand EQUIVALENCE) from the list of features to be designated as obsolescent (as theyare now known). A series of votes definitively removed from the language all plansto add: arrays of arrays, exception handling, nesting of internal procedures, theFORALL statement (now in Fortran 95), and a means to access skew array sections.There were other features on this list that, although removed, were reinstated atlater meetings: user-defined operators, operator overloading, array and structureconstructors, and vector-valued subscripts. After many more travails, the committeevoted, a year later, by 26 votes to 9, to forward the document for what was to becomethe first of three periods of public comment.

    While the document was going through the formal standards bureaucracy andbeing placed before the public, X3J3 polished it further. X3J3 also preparedprocedures for processing the comments it anticipated receiving from the public,and to each of which, under the rules, it would have to reply individually. It wasjust as well. Roughly 400 replies flooded in, many of them very detailed and,disappointingly for those of us wanting a new standard quickly, unquestionablynegative towards our work. For many it was too radical, but many others pleadedfor yet more modern features, such as pointers.

    Now the committee was deadlocked. Given that a document had alreadybeen published, any further change required not a simple but a two-thirds majority.The conservatives and the radicals could each block a move to modify the draftstandard, or to accept a revised one for public review and just that happened,in Champagne-Urbana, Illinois, in 1988. Any change, be it on the one hand tomodify the list of obsolescent features, to add the pointers or bit data type wantedby the public, to add multi-byte characters to support Kanji and other non-Europeanlanguages or, on the other hand, to emasculate the language by removing modules oroperator overloading, and hence abstract data types, to name but some suggestions,none of these could be done individually or collectively in a way that would achieveconsensus. I wrote:

    In my opinion, no standard can now emerge without either a huge concessionby the users to the vendors (MODULE / USE) and/or a major change in the compositionof the committee. I do not see how members who have worked for up to a decade

  • Foreword xiiiSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).or more, devoting time and intellectual energy far beyond the call of duty, can beexpected to make yet more personal sacrifices if no end to the work is in sight, orif that end is nothing but a travesty of what had been designed and intended as amodern scientific programming language. . . . I think the August meeting will be awatershed if no progress is achieved there will be dramatic resignations, and ISOcould even remove the work from ANSI, which is failing conspicuously in its task."

    (However, the same notes began with a quotation from The Taming of theShrew: And do as adversaries do in law, / Strive mightily, but eat and drink / asfriend." That we always did, copiously.)

    Resolution

    The August meeting was, unexpectedly, imbued with a spirit of compromisethat had been so sadly lacking at the previous one. Nevertheless, after a week ofdiscussing four separate plans to rescue the standard, no agreement was reached.Now the question seriously arose: Was X3J3 incapable of producing a new Fortranstandard for the international community, doomed to eternal deadlock, a victim ofANSI procedures?

    Breakthrough was achieved at a traumatic meeting of WG5 in Paris, France, amonth later. The committee spent several extraordinary days drawing up a detailedlist of what it wanted to be in Fortran 8x. Finally, it set X3J3 an ultimatum that wasunprecedented in the standards world: The ANSI committee was to produce a newdraft document, corresponding to WG5s wishes, within five months! Failing that,WG5 would assume responsibility and produce the new standard itself.

    This decision was backed by the senior U.S. committee, X3, which effectivelydirected X3J3 to carry out WG5s wishes. And it did! The following November, itimplemented most of the technical changes, adding pointers, bit manipulation intrin-sic procedures, and vector-valued subscripts, and removing user-defined elementalfunctions (now in Fortran 95). The actual list of changes was much longer. X3J3 andWG5, now collaborating closely, often in gruelling six-day meetings, spent the next18 months and two more periods of (positive) public comment putting the finishingtouches to what was now called Fortran 90, and it was finally adopted, after somecliff-hanging votes, for forwarding as a U.S. and international standard on April 11,1991, in Minneapolis, Minnesota.

    Among the remaining issues that were decided along the way were whetherpointers should be a data type or be defined in terms of an attribute of a variable,implying strong typing (the latter was chosen), whether the new standard shouldcoexist alongside the old one rather than definitively replace it (it coexisted for awhile in the U.S., but was a replacement elsewhere, under ISO rules), and whether,in the new free source form, blanks should be significant (fortunately, they are).

    Fortran 90

    The main new features of Fortran 90 are, first and foremost, the array languageand abstract data types. The first is built on whole array operations and assignments,array sections, intrinsic procedures for arrays, and dynamic storage. It was designedwith optimization in mind. The second is built on modules and module procedures,derived data types, operator overloading and generic interfaces, together with

  • xiv ForewordSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).pointers. Also important are the new facilities for numerical computation includinga set of numeric inquiry functions, the parametrization of the intrinsic types, newcontrol constructs SELECT CASE and new forms of DO, internal and recursiveprocedures and optional and keyword arguments, improved I/O facilities, and manynew intrinsic procedures. Last but not least are the new free source form, animproved style of attribute-oriented specifications, the IMPLICIT NONE statement,and a mechanism for identifying redundant features for subsequent removal from thelanguage. The requirement on compilers to be able to identify, for example, syntaxextensions, and to report why a program has been rejected, are also significant. Theresulting language is not only a far more powerful tool than its successor, but a saferand more reliable one too. Storage association, with its attendant dangers, is notabolished, but rendered unnecessary. Indeed, experience shows that compilers detecterrors far more frequently than before, resulting in a faster development cycle. Thearray syntax and recursion also allow quite compact code to be written, a furtheraid to safe programming.

    No programming language can succeed if it consists simply of a definition(witness Algol 68). Also required are robust compilers from a wide variety ofvendors, documentation at various levels, and a body of experience. The first Fortran90 compiler appeared surprisingly quickly, in 1991, especially in view of the widelytouted opinion that it would be very difficult to write one. Even more remarkablewas that it was written by one person, Malcolm Cohen of NAG, in Oxford, U.K.There was a gap before other compilers appeared, but now they exist as nativeimplementations for almost all leading computers, from the largest to PCs. For themost part, they produce very efficient object code; where, for certain new features,this is not the case, work is in progress to improve them.

    The first book, Fortran 90 Explained, was published by John Reid and meshortly before the standard itself was published. Others followed in quick succession,including excellent texts aimed at the college market. At the time of writing thereare at least 19 books in English and 22 in various other languages: Chinese, Dutch,French, Japanese, Russian, and Swedish. Thus, the documentation condition isfulfilled.

    The body of experience, on the other hand, has yet to be built up to a critical size.Teaching of the language at college level has only just begun. However, I am certainthat this present volume will contribute decisively to a significant breakthrough, as itprovidesmodels not only of the numerical algorithms for which previous editions arealready famed, but also of an excellent Fortran 90 style, something that can developonly with time. Redundant features are abjured. It shows that, if we abandon thesefeatures and use new ones in their place, the appearance of code can initially seemunfamiliar, but, in fact, the advantages become rapidly apparent. This new editionof Numerical Recipes stands as a landmark in this regard.

    Fortran Evolution

    The formal procedures under which languages are standardized require themeither to evolve or to die. A standard that has not been revised for some years musteither be revised and approved anew, or be withdrawn. This matches the technicalpressure on the language developers to accommodate the increasing complexity bothof the problems to be tackled in scientific computation and of the underlyinghardware

  • Foreword xvSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).on which programs run. Increasing problem complexity requires more powerfulfeatures and syntax; new hardware needs language features that map onto it well.

    Thus it was that X3J3 and WG5, having finished Fortran 90, began a new roundof improvement. They decided very quickly on new procedures that would avoidthe disputes that bedevilled the previous work: WG5 would decide on a plan forfuture standards, and X3J3 would act as the so-called development body that wouldactually produce them. This would be done to a strict timetable, such that any featurethat could not be completed on time would have to wait for the next round. It wasfurther decided that the next major revision should appear a decade after Fortran 90but, given the somewhat discomforting number of requests for interpretation that hadarrived, about 200, that a minor revision should be prepared for mid-term, in 1995.This should contain only corrections, clarifications and interpretations and a verylimited number (some thought none) of minor improvements.

    At the same time, scientific programmerswere becoming increasingly concernedat the variety of methods that were necessary to gain efficient performance from theever-more widely used parallel architectures. Each vendor provided a different setof parallel extensions for Fortran, and some academic researchers had developed yetothers. On the initiative of Ken Kennedy of Rice University, a High-PerformanceFortran Forum was established. A coalition of vendors and users, its aim was toproduce an ad hoc set of extensions to Fortran that would become an informal butwidely accepted standard for portable code. It set itself the daunting task of achievingthat in just one year, and succeeded. Melding existing dialects like Fortran D, CMFortran, and Vienna Fortran, and adopting the new Fortran 90 as a base, becauseof its array syntax, High-Performance Fortran (HPF) was published in 1993 andhas since become widely implemented. However, although HPF was designed fordata parallel codes and mainly implemented in the form of directives that appearto non-HPF processors as comment lines, an adequate functionality could not beachieved without extending the Fortran syntax. This was done in the form of thePURE attribute for functionsan assertion that they contain no side effects and theFORALL construct a form of array assignment expressed with the help of indices.

    The dangers of having diverging or competing forms of Fortran 90 wereimmediately apparent, and the standards committees wisely decided to incorporatethese two syntactic changes also into Fortran 95. But they didnt stop there. Twofurther extensions, useful not only for their expressive power but also to accessparallel hardware, were added: elemental functions, ones written in terms of scalarsbut that accept array arguments of any permitted shape or size, and an extension toallow nesting of WHERE constructs, Fortrans form of masked assignment. To readersof Numerical Recipes, perhaps the most relevant of the minor improvements thatFortran 95 brings are the ability to distinguish between a negative and a positive realzero, automatic deallocation of allocatable arrays, and a means to initialize the valuesof components of objects of derived data types and to initialize pointers to null.

    The medium-term objective of a relatively minor upgrade has been achieved onschedule. But what does the future hold? Developments in the underlying principlesof procedural programming languages have not ceased. Early Fortran introduced theconcepts of expression abstraction (X=Y+Z) and later control expression (e.g., the DOloop). Fortran 77 continued this with the if-then-else, and Fortran 90 with theDO and SELECT CASE constructs. Fortran 90 has a still higher level of expressionabstraction (array assignments and expressions) as well as data structures and even

  • xvi ForewordSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).full-blown abstract data types. However, during the 1980s the concept of objectscame to the fore, with methods bound to the objects on which they operate. Here,one particular language, C++, has come to dominate the field. Fortran 90 lacksa means to point to functions, but otherwise has most of the necessary features inplace, and the standards committees are now faced with the dilemma of decidingwhether to make the planned Fortran 2000 a fully object-oriented language. Thiscould possibly jeopardize its powerful, and efficient, numerical capabilities by toogreat an increase in language complexity, so should they simply batten down thehatches and not defer to what might be only a passing storm? At the time of writing,this is an open issue. One issue that is not open is Fortrans lack of in-built exceptionhandling. It is virtually certain that such a facility, much requested by the numericalcommunity, and guided by John Reid, will be part of the next major revision. Thelist of other requirements is long but speculative, but some at the top of the listare conditional compilation, command line argument handling, I/O for objects ofderived type, and asynchronous I/O (which is also planned for the next releaseof HPF). In the meantime, some particularly pressing needs have been identified,for the handling of floating-point exceptions, interoperability with C, and allowingallocatable arrays as structure components, dummy arguments, and function results.These have led WG5 to begin processing these three items using a special form offast track, so that they might become optional but standard extensions well beforeFortran 2000 itself is published in the year 2001.

    Conclusion

    Writing a book is always something of a gamble. Unlike a novel that standsor falls on its own, a book devoted to a programming language is dependent onthe success of others, and so the risk is greater still. However, this new NumericalRecipes in Fortran 90 volume is no ordinary book, since it comes as the continuationof a highly successful series, and so great is its significance that it can, in fact,influence the outcome in its own favor. I am entirely confident that its publicationwill be seen as an important event in the story of Fortran 90, and congratulate itsauthors on having performed a great service to the field of numerical computing.

    Geneva, SwitzerlandJanuary 1996

    Michael Metcalf

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    License Information

    Read this section if you want to use the programs in this book on a computer.Youll need to read the followingDisclaimer ofWarranty, get the programs onto yourcomputer, and acquire a Numerical Recipes software license. (Without this license,which can be the free immediate license under terms described below, the book isintended as a text and reference book, for reading purposes only.)

    Disclaimer of Warranty

    We make no warranties, express or implied, that the programs containedin this volume are free of error, or are consistent with any particular standardof merchantability, or that they will meet your requirements for any particularapplication. They should not be relied on for solving a problem whose incorrectsolution could result in injury to a person or loss of property. If you do use theprograms in such a manner, it is at your own risk. The authors and publisherdisclaim all liability for direct or consequential damages resulting from youruse of the programs.

    How to Get the Code onto Your Computer

    Pick one of the following methods:

    You can type the programs from this book directly into your computer. Inthis case, the only kind of license available to you is the free immediatelicense (see below). You are not authorized to transfer or distribute amachine-readable copy to any other person, nor to have any other persontype the programs into a computer on your behalf. We do not want to hearbug reports from you if you choose this option, because experience hasshown that virtually all reported bugs in such cases are typing errors!

    You can download the Numerical Recipes programs electronically fromthe Numerical Recipes On-Line Software Store, located at our Web site(http://www.nr.com). They are packaged as a password-protectedfile, and youll need to purchase a license to unpack them. You canget a single-screen license and password immediately, on-line, from theOn-Line Store, with fees ranging from $50 (PC, Macintosh, educationalinstitutions UNIX) to $140 (general UNIX). Downloading the packagedsoftware from the On-Line Store is also the way to start if you want toacquire a more general (multiscreen, site, or corporate) license.

    You can purchase media containing the programs from Cambridge Uni-versity Press. Diskette versions are available in IBM-compatible formatfor machines running Windows 3.1, 95, or NT. CDROM versions in ISO-9660 format for PC, Macintosh, and UNIX systems are also available;these include both Fortran and C versions (as well as versions in Pascal

    xvii

  • xviii License InformationSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).and BASIC from the first edition) on a single CDROM. Diskettes pur-chased from Cambridge University Press include a single-screen licensefor PC or Macintosh only. The CDROM is available with a single-screen license for PC or Macintosh (order ISBN 0 521 576083), or (at aslightly higher price) with a single-screen license for UNIX workstations(order ISBN 0 521 576075). Orders for media from Cambridge Univer-sity Press can be placed at 800 872-7423 (North America only) or byemail to [email protected] (North America) or [email protected] (restof world). Or, visit the Web sites http://www.cup.org (NorthAmerica)or http://www.cup.cam.ac.uk (rest of world).

    Types of License Offered

    Here are the types of licenses that we offer. Note that some types areautomatically acquired with the purchase of media from Cambridge UniversityPress, or of an unlocking password from the Numerical Recipes On-Line SoftwareStore, while other types of licenses require that you communicate specifically withNumerical Recipes Software (email: [email protected] or fax: 781 863-1739). OurWeb site http://www.nr.com has additional information.

    [Immediate License] If you are the individual owner of a copy of thisbook and you type one or more of its routines into your computer, weauthorize you to use them on that computer for your own personal andnoncommercial purposes. You are not authorized to transfer or distributemachine-readable copies to any other person, or to use the routines onmore than one machine, or to distribute executable programs containingour routines. This is the only free license.

    [Single-Screen License] This is the most common type of low-costlicense, with terms governed by our Single Screen (Shrinkwrap) Licensedocument (complete terms available through ourWeb site). Basically, thislicense lets you use Numerical Recipes routines on any one screen (PC,workstation, X-terminal, etc.). You may also, under this license, transferpre-compiled, executable programs incorporating our routines to other,unlicensed, screens or computers, providing that (i) your application isnoncommercial (i.e., does not involve the selling of your program for afee), (ii) the programs were first developed, compiled, and successfullyrun on a licensed screen, and (iii) our routines are bound into the programsin such a manner that they cannot be accessed as individual routines andcannot practicably be unbound and used in other programs. That is, underthis license, your program user must not be able to use our programs aspart of a program library or mix-and-match workbench. Conditions forother types of commercial or noncommercial distribution may be foundon our Web site (http://www.nr.com).

    [Multi-Screen, Server, Site, and Corporate Licenses] The terms ofthe Single Screen License can be extended to designated groups ofmachines, defined by number of screens, number of machines, locations,or ownership. Significant discounts from the corresponding single-screen

  • License Information xixSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).prices are available when the estimated number of screens exceeds 40.Contact Numerical Recipes Software (email: [email protected] or fax: 781863-1739) for details.

    [Course Right-to-Copy License] Instructors at accredited educationalinstitutions who have adopted this book for a course, and who havealready purchased a Single Screen License (either acquired with thepurchase of media, or from the Numerical Recipes On-Line SoftwareStore), may license the programs for use in that course as follows: Mailyour name, title, and address; the course name, number, dates, andestimated enrollment; and advance payment of $5 per (estimated) studentto Numerical Recipes Software, at this address: P.O. Box 243, Cambridge,MA 02238 (USA). You will receive by return mail a license authorizingyou to make copies of the programs for use by your students, and/or totransfer the programs to a machine accessible to your students (but onlyfor the duration of the course).

    About Copyrights on Computer Programs

    Like artistic or literary compositions, computer programs are protected bycopyright. Generally it is an infringement for you to copy into your computer aprogram from a copyrighted source. (It is also not a friendly thing to do, since itdeprives the programs author of compensation for his or her creative effort.) Undercopyright law, all derivative works (modified versions, or translations into anothercomputer language) also come under the same copyright as the original work.

    Copyright does not protect ideas, but only the expression of those ideas ina particular form. In the case of a computer program, the ideas consist of theprograms methodology and algorithm, including the necessary sequence of stepsadopted by the programmer. The expression of those ideas is the program sourcecode (particularly any arbitrary or stylistic choices embodied in it), its derived objectcode, and any other derivative works.

    If you analyze the ideas contained in a program, and then express thoseideas in your own completely different implementation, then that new programimplementation belongs to you. That is what we have done for those programs inthis book that are not entirely of our own devising. When programs in this book aresaid to be based on programs published in copyright sources, we mean that theideas are the same. The expression of these ideas as source code is our own. Webelieve that no material in this book infringes on an existing copyright.

    Trademarks

    Several registered trademarks appear within the text of this book: Sun is atrademark of Sun Microsystems, Inc. SPARC and SPARCstation are trademarks ofSPARC International, Inc. Microsoft, Windows 95, Windows NT, PowerStation,and MS are trademarks of Microsoft Corporation. DEC, VMS, Alpha AXP, andULTRIX are trademarks of Digital Equipment Corporation. IBM is a trademark ofInternational Business Machines Corporation. Apple and Macintosh are trademarksof Apple Computer, Inc. UNIX is a trademark licensed exclusively through X/Open

  • xx License InformationSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).Co. Ltd. IMSL is a trademark of Visual Numerics, Inc. NAG refers to proprietarycomputer software of Numerical Algorithms Group (USA) Inc. PostScript andAdobe Illustrator are trademarks of Adobe Systems Incorporated. Last, and no doubtleast, Numerical Recipes (when identifying products) is a trademark of NumericalRecipes Software.

    Attributions

    The fact that ideas are legally free as air in no way supersedes the ethicalrequirement that ideas be credited to their known originators. When programs inthis book are based on known sources, whether copyrighted or in the public domain,published or handed-down, we have attempted to give proper attribution. Unfor-tunately, the lineage of many programs in common circulation is often unclear. Wewould be grateful to readers for new or corrected information regarding attributions,which we will attempt to incorporate in subsequent printings.

  • Sample page from

    NU

    MER

    ICAL R

    ECIPES IN

    FOR

    TRAN

    90: The Art of PARALLEL Scientific C

    omputing (ISBN

    0-521-57439-0)C

    opyright (C) 1986-1996 by C

    ambridge U

    niversity Press.Programs C

    opyright (C) 1986-1996 by N

    umerical R

    ecipes Software.

    Permission is granted for internet users to m

    ake one paper copy for their own personal use. Further reproduction, or any copying of m

    achine-readable files (including this one) to any servercom

    puter, is strictly prohibited. To order Num

    erical Recipes books,diskettes, or C

    DR

    OM

    svisit w

    ebsite http://ww

    w.nr.com

    or call 1-800-872-7423 (North Am

    erica only),or send email to trade@

    cup.cam.ac.uk (outside N

    orth America).

    Chapter 21. Introductionto Fortran 90Language Features

    21.0 Introduction

    Fortran 90 is in many respects a backwards-compatible modernization of thelong-used (and much abused) Fortran 77 language, but it is also, in other respects,a new language for parallel programming on present and future multiprocessormachines. These twin design goals of the language sometimes add confusion to theprocess of becoming fluent in Fortran 90 programming.

    In a certain trivial sense, Fortran 90 is strictly backwards-compatible withFortran 77. That is, any Fortran 90 compiler is supposed to be able to compile anylegacy Fortran 77 code without error. The reason for terming this compatibilitytrivial, however, is that you have to tell the compiler (usually via a source file nameending in .f or .for) that it is dealing with a Fortran 77 file. If you insteadtry to pass off Fortran 77 code as native Fortran 90 (e.g., by naming the source filesomething ending in .f90) it will not always work correctly!

    It is best, therefore, to approach Fortran 90 as a new computer language, albeitone with a lot in common with Fortran 77. Indeed, in such terms, Fortran 90 is afairly big language, with a large number of new constructions and intrinsic functions.Here, in one short chapter, we do not pretend to provide a complete description ofthe language. Luckily, there are good books that do exactly that. Our favorite oneis by Metcalf and Reid [1], cited throughout this chapter as M&R. Other goodstarting points include [2] and [3].

    Our goal, in the remainder of this chapter, is to give a good, working descriptionof those Fortran 90 language features that are not immediately self-explanatoryto Fortran 77 programmers, with particular emphasis on those that occur mostfrequently in the Fortran 90 versions of the Numerical Recipes routines. Thischapter, by itself, will not teach you to write Fortran 90 code. But it ought to helpyou acquire a reading knowledge of the language, and perhaps provide enough ofa head start that you can rapidly pick up the rest of what you need to know fromM&R or another Fortran 90 reference book.

    CITED REFERENCES AND FURTHER READING:Metcalf, M., and Reid, J. 1996, Fortran 90/95 Explained (Oxford: Oxford University Press). [1]

    935

  • 936 Chapter 21. Introduction to Fortran 90 Language FeaturesSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).Kerrigan, J.F. 1993, Migrating to Fortran 90 (Sebastopol, CA: OReilly). [2]Brainerd, W.S., Goldberg, C.H., and Adams, J.C. 1996, Programmers Guide to Fortran 90, 3rd

    ed. (New York: Springer-Verlag). [3]

    21.1 Quick Start: Using the Fortran 90Numerical Recipes Routines

    This section is for people who want to jump right in. Well compute a Besselfunction J0(x), where x is equal to the fourth root of the Julian Day number of the200th full moon since January 1900. (Now theres a useful quantity!)

    First, locate the important files nrtype.f90, nrutil.f90, and nr.f90, aslisted in Appendices C1, C1, and C2, respectively. These contain modules thateither are (i) used by our routines, or else (ii) describe the calling conventions of ourroutines to (your) user programs. Compile each of these files, producing (with mostcompilers) a .mod file and a .o (or similarly named) file for each one.

    Second, create this main program file:PROGRAM hello_besselUSE nrtypeUSE nr, ONLY: flmoon, bessj0IMPLICIT NONEINTEGER(I4B) :: n=200,nph=2,jdREAL(SP) :: x,frac,anscall flmoon(n,nph,jd,frac)x=jd**0.25_spans=bessj0(x)write (*,*) Hello, Bessel: , ansEND PROGRAM

    Here is a quick explanation of some elements of the above program:The first USE statement includes a module of ours named nrtype, whose purpose is to

    give symbolic names to some kinds of data types, among them single-precision reals (sp)and four-byte integers (i4b). The second USE statement includes a module of ours thatdefines the calling sequences, and variable types, expected by (in this case) the NumericalRecipes routines flmoon and bessj0.

    The IMPLICIT NONE statement signals that we want the compiler to require us explicitlyto declare all variable types. We strongly urge that you always take this option.

    The next two lines declare integer and real variables of the desired kinds. The variablen is initialized to the value 200, nph to 2 (a value expected by flmoon).

    We call flmoon, and take the fourth root of the answer it returns as jd. Note that theconstant 0.25 is typed to be single-precision by the appended sp.

    We call the bessj0 routine, and print the answer.

    Third, compile the main program file, and also the files flmoon.f90,bessj0.f90. Then, link the resulting object files with also nrutil.o (or sim-ilar system-dependent name, as produced in step 1). Some compilers will alsorequire you to link with nr.o and nrtype.o.

    Fourth, run the resulting executable file. Typical output is:Hello, Bessel: 7.3096365E-02

  • 21.2 Fortran 90 Language Concepts 937Sam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).

    21.2 Fortran 90 Language Concepts

    The Fortran 90 language standard defines and uses a number of standard termsfor concepts that occur in the language. Here we summarize briefly some of themost important concepts. Standard Fortran 90 terms are shown in italics. While byno means complete, the information in this section should help you get a quick startwith your favorite Fortran 90 reference book or language manual.

    A note on capitalization: Outside a character context, Fortran 90 is not case-sensitive, so you can use upper and lower case any way you want, to improvereadability. A variable like SP (see below) is the same variable as the variable sp.We like to capitalize keywords whose use is primarily at compile-time (statementsthat delimit program and subprogram boundaries, declaration statements of variables,fixed parameter values), and use lower case for the bulk of run-time code. You canadopt any convention that you find helpful to your own programming style; but westrongly urge you to adopt and follow some convention.

    Data Types and Kinds

    Data types (also called simply types) can be either intrinsic data types (thefamiliar INTEGER, REAL, LOGICAL, and so forth) or else derived data types that arebuilt up in the manner of what are called structures or records in other computerlanguages. (Well use derived data types very sparingly in this book.) Intrinsic datatypes are further specified by their kind parameter (or simply kind), which is simplyan integer. Thus, on many machines, REAL(4) (with kind = 4) is a single-precisionreal, while REAL(8) (with kind = 8) is a double-precision real. Literal constants(or simply literals) are specified as to kind by appending an underscore, as 1.5 4for single precision, or 1.5 8 for double precision. [M&R, 2.52.6]

    Unfortunately, the specific integer values that define the different kind typesare not specified by the language, but can vary from machine to machine. Forthat reason, one almost never uses literal kind parameters like 4 or 8, but ratherdefines in some central file, and imports into all ones programs, symbolic namesfor the kinds. For this book, that central file is the module named nrtype, and thechosen symbolic names include SP, DP (for reals); I2B, I4B (for two- and four-byteintegers); and LGT for the default logical type. You will therefore see us consistentlywriting REAL(SP), or 1.5 sp, and so forth.

    Here is an example of declaring some variables, including a one-dimensionalarray of length 500, and a two-dimensional array with 100 rows and 200 columns:

    USE nrtypeREAL(SP) :: x,y,zINTEGER(I4B) :: i,j,kREAL(SP), DIMENSION(500) :: arrREAL(SP), DIMENSION(100,200) :: barrREAL(SP) :: carr(500)

    The last line shows an alternative form for array syntax. And yes, there are defaultkind parameters for each intrinsic type, but these vary from machine to machine andcan get you into trouble when you try to move code. We therefore specify all kindparameters explicitly in almost all situations.

  • 938 Chapter 21. Introduction to Fortran 90 Language FeaturesSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).Array Shapes and Sizes

    The shape of an array refers to both its dimensionality (called its rank), andalso the lengths along each dimension (called the extents). The shape of an array isspecified by a rank-one array whose elements are the extents along each dimension,and can be queried with the shape intrinsic (see p. 949). Thus, in the above example,shape(barr) returns an array of length 2 containing the values (100, 200).

    The size of an array is its total number of elements, so the intrinsic size(barr)would return 20000 in the above example. More often one wants to know theextents along each dimension, separately: size(barr,1) returns the value 100,while size(barr,2) returns the value 200. [M&R, 2.10]

    Section 21.3, below, discusses additional aspects of arrays in Fortran 90.

    Memory Management

    Fortran 90 is greatly superior to Fortran 77 in its memory-management capa-bilities, seen by the user as the ability to create, expand, or contract workspace forprograms. Within subprograms (that is, subroutines and functions), one can haveautomatic arrays (or other automatic data objects) that come into existence eachtime the subprogram is entered, and disappear (returning their memory to the pool)when the subprogram is exited. The size of automatic objects can be specifiedby arbitrary expressions involving values passed as actual arguments in the callingprogram, and thus received by the subprogram through its corresponding dummyarguments. [M&R, 6.4]

    Here is an example that creates some automatic workspace named carr:

    SUBROUTINE dosomething(j,k)USE nrtypeREAL(SP), DIMENSION(2*j,k**2) :: carr

    Finer control on when workspace is created or destroyed can be achieved bydeclaring allocatable arrays, which exist as names only, without associated memory,until they are allocatedwithin the program or subprogram. When no longer needed,they can be deallocated. The allocation status of an allocatable array can be testedby the program via the allocated intrinsic function (p. 952). [M&R, 6.5]

    Here is an example in outline:

    REAL(SP), DIMENSION(:,:), ALLOCATABLE :: darr...allocate(darr(10,20))...deallocate(darr)...allocate(darr(100,200))...deallocate(darr)

    Notice that darr is originally declared with only slots (colons) for its dimensions,and is then allocated/deallocated twice, with different sizes.

    Yet finer control is achieved by the use of pointers. Like an allocatable array,a pointer can be allocated, at will, its own associated memory. However, it hasthe additional flexibility of alternatively being pointer associated with a target that

  • 21.2 Fortran 90 Language Concepts 939Sam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).already exists under another name. Thus, pointers can be used as redefinable aliasesfor other variables, arrays, or (see 21.3) array sections. [M&R, 6.12]

    Here is an example that first associates the pointer parr with the array earr,then later cancels that association and allocates it its own storage of size 50:

    REAL(SP), DIMENSION(:), POINTER :: parrREAL(SP), DIMENSION(100), TARGET :: earr...parr => earr...nullify(parr)allocate(parr(50))...deallocate(parr)

    Procedure InterfacesWhen a procedure is referenced (e.g., called) from within a program or

    subprogram (examples of scoping units), the scoping unit must be told, or mustdeduce, the procedures interface, that is, its calling sequence, including the typesand kinds of all dummy arguments, returned values, etc. The recommendedprocedure is to specify this interface via an explicit interface, usually an interfaceblock (essentially a declaration statement for subprograms) in the calling subprogramor in some module that the calling program includes via a USE statement. In thisbook all interfaces are explicit, and the module named nr contains interface blocksfor all of the Numerical Recipes routines. [M&R, 5.11]

    Here is a typical example of an interface block:INTERFACE

    SUBROUTINE caldat(julian,mm,id,iyyy)USE nrtypeINTEGER(I4B), INTENT(IN) :: julianINTEGER(I4B), INTENT(OUT) :: mm,id,iyyyEND SUBROUTINE caldat

    END INTERFACE

    Once this interface is made known to a program that you are writing (by eitherexplicit inclusion or a USE statement), then the compiler is able to flag for you avariety of otherwise difficult-to-find bugs. Although interface blocks can sometimesseem overly wordy, they give a big payoff in ultimately minimizing programmertime and frustration.

    For compatibility with Fortran 77, the language also allows for implicit inter-faces, where the calling program tries to figure out the interface by the old rules ofFortran 77. These rules are quite limited, and prone to producing devilishly obscureprogram bugs. We strongly recommend that implicit interfaces never be used.

    Elemental Procedures and Generic InterfacesMany intrinsic procedures (those defined by the language standard and thus

    usable without any further definition or specification) are also generic. This meansthat a single procedure name, such as log(x), can be used with a variety of typesand kind parameters for the argument x, and the result returned will have the sametype and kind parameter as the argument. In this example, log(x) allows any realor complex argument type.

  • 940 Chapter 21. Introduction to Fortran 90 Language FeaturesSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).Better yet, most generic functions are also elemental. The argument of an

    elemental function can be an array of arbitrary shape! Then, the returned result isan array of the same shape, with each element containing the result of applying thefunction to the corresponding element of the argument. (Hence the name elemental,meaning applied element by element.) [M&R, 8.1] For example:

    REAL(SP), DIMENSION(100,100) :: a,bb=sin(a)

    Fortran 90 has no facility for creating new, user-defined elemental functions.It does have, however, the related facility of overloading by the use of genericinterfaces. This is invoked by the use of an interface block that attaches a singlegeneric name to a number of distinct subprograms whose dummy arguments havedifferent types or kinds. Then, when the generic name is referenced (e.g., called),the compiler chooses the specific subprogram that matches the types and kinds of theactual arguments used. [M&R, 5.18] Here is an example of a generic interface block:

    INTERFACE myfuncFUNCTION myfunc_single(x)USE nrtypeREAL(SP) :: x,myfunc_singleEND FUNCTION myfunc_single

    FUNCTION myfunc_double(x)USE nrtypeREAL(DP) :: x,myfunc_doubleEND FUNCTION myfunc_double

    END INTERFACE

    A program with knowledge of this interface could then freely use the functionreference myfunc(x) for xs of both type SP and type DP.

    We use overloading quite extensively in this book. A typical use is to provide,under the same name, both scalar and vector versions of a function such as aBessel function, or to provide both single-precision and double-precision versionsof procedures (as in the above example). Then, to the extent that we have providedall the versions that you need, you can pretend that our routine is elemental. Insuch a situation, if you ever call our function with a type or kind that we havenot provided, the compiler will instantly flag the problem, because it is unable toresolve the generic interface.

    ModulesModules, already referred to several times above, are Fortran 90s generalization

    of Fortran 77s common blocks, INCLUDEd files of parameter statements, and (tosome extent) statement functions. Modules are program units, like main programs orsubprograms (subroutines and functions), that can be separately compiled. Amoduleis a convenient place to stash global data, named constants (what in Fortran 77are called symbolic constants or PARAMETERs), interface blocks to subprogramsand/or actual subprograms themselves (module subprograms). The convenience isthat a modules information can be incorporated into another program unit via asimple, one-line USE statement. [M&R, 5.5]

    Here is an example of a simple module that defines a few parameters, createssome global storage for an array named arr (as might be done with a Fortran 77common block), and defines the interface to a function yourfunc:

  • 21.3 More on Arrays and Array Sections 941Sam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).MODULE mymodule

    USE nrtypeREAL(SP), PARAMETER :: con1=7.0_sp/3.0_sp,con2=10.0_spINTEGER(I4B), PARAMETER :: ndim=10,mdim=9REAL(SP), DIMENSION(ndim,mdim) :: arrINTERFACE

    FUNCTION yourfunc(x)USE nrtypeREAL(SP) :: x,yourfuncEND FUNCTION yourfunc

    END INTERFACEEND MODULE mymodule

    As mentioned earlier, the module nr contains INTERFACE declarations for allthe Numerical Recipes. When we include a statement of the form

    USE nr, ONLY: recipe1

    it means that the program uses the additional routine recipe1. The compiler isable to use the explicit interface declaration in the module to check that recipe1 isinvokedwith arguments of the correct type, shape, and number. However, a weaknessof Fortran 90 is that there is no fail-safe way to be sure that the interface module(here nr) stays synchronized with the underlying routine (here recipe1). You mightthink that you could accomplish this by putting USE nr, ONLY: recipe1 into therecipe1 program itself. Unfortunately, the compiler interprets this as an erroneousdouble definition of recipe1s interface, rather than (as would be desirable) as anopportunity for a consistency check. (To achieve this kind of consistency check, youcan put the procedures themselves, not just their interfaces, into the module.)

    CITED REFERENCES AND FURTHER READING:Metcalf, M., and Reid, J. 1996, Fortran 90/95 Explained (Oxford: Oxford University Press).

    21.3 More on Arrays and Array Sections

    Arrays are the central conceptual core of Fortran 90 as a parallel programminglanguage, and thus worthy of some further discussion. We have already seen thatarrays can come into existence in Fortran 90 in several ways, either directlydeclared, as

    REAL(SP), DIMENSION(100,200) :: arr

    or else allocated by an allocatable variable or a pointer variable,REAL(SP), DIMENSION(:,:), ALLOCATABLE :: arrREAL(SP), DIMENSION(:,:), POINTER :: barr...allocate(arr(100,200),barr(100,200))

    or else (not previously mentioned) passed into a subprogram through a dummyargument:

    SUBROUTINE myroutine(carr)USE nrtypeREAL(SP), DIMENSION(:,:) :: carr...i=size(carr,1)

  • 942 Chapter 21. Introduction to Fortran 90 Language FeaturesSam

    ple page from N

    UM

    ERIC

    AL REC

    IPES IN FO

    RTR

    AN 90: The Art of PAR

    ALLEL Scientific Com

    puting (ISBN 0-521-57439-0)

    Copyright (C

    ) 1986-1996 by Cam

    bridge University Press.Program

    s Copyright (C

    ) 1986-1996 by Num

    erical Recipes Softw

    are. Perm

    ission is granted for internet users to make one paper copy for their ow

    n personal use. Further reproduction, or any copying of machine-

    readable files (including this one) to any servercomputer, is strictly prohibited. To order N

    umerical R

    ecipes books,diskettes, or CD

    RO

    Ms

    visit website http://w

    ww

    .nr.com or call 1-800-872-7423 (N

    orth America only),or send em

    ail to [email protected]

    .ac.uk (outside North Am

    erica).j=size(carr,2)

    In the above example we also show how the subprogram can find out the size ofthe actual array that is passed, using the size intrinsic. This routine is an exampleof the use of an assumed-shape array, new to Fortran 90. The actual extents alongeach dimension are inherited from the calling routine at run time. A subroutinewith assumed-shape array arguments must have an explicit interface in the callingroutine, otherwise the compiler doesnt know about the extra information that mustbe passed. A typical setup for calling myroutine would be:

    PROGRAM use_myroutineUSE nrtypeREAL(SP), DIMENSION(10,10) :: arrINTERFACE

    SUBROUTINE myroutine(carr)USE nrtypeREAL(SP), DIMENSION(:,:) :: carrEND SUBROUTINE myroutine

    END INTERFACE...call myroutine(a)

    Of course, for the recipes we have provided all the interface blocks in the file nr.f90,and you need only a USE nr statement in your calling program.