An Introduction to Fortran 90 2.1 About Fortran in General

Total Page:16

File Type:pdf, Size:1020Kb

An Introduction to Fortran 90 2.1 About Fortran in General 2 An Introduction to Fortran 90 This chapter aims at giving a short introduction to Fortran 90. As describing all features of the Fortran language would probably fill some hundred pages, we will concentrate on the basic features that will be needed to follow the rest of this textbook. Nevertheless, there are various Fortran tutorials out in the internet that could be used as complementary literature. 2.1 About Fortran in general 2.1.1 The history of Fortran Fortran is pretty old. Actually it is considered the first realized higher programming lan- guage. It goes back to a proposal by John W. Backus, an IBM programmer, in 1953. The term Fortran is derived from The IBM Formula Translation System. Before the release of the first Fortran compiler in April 1957, people used to use assembly languages. The intro- duction of a higher programming language compiler reduced the number of code lines needed to write a program tremendously and therefore FORTRAN, the first release of the Fortran programming language, grew pretty fast in popularity. From 1957 on several versions followed the initial FORTRAN version, namely FORTRAN II and FORTRAN III in 1958 and FORTRAN IV in 1961. In 1966, the American Standards Association (now known as the ANSI) approved a standardized American Standard Fortran.Theprogram- ming language defined on this standard was called FORTRAN 66. Approving an updated standard in 1977, the ANSI paved the way for a new Fortran version known as FORTRAN 77. This version became pretty popular in computational economics during the 80ies and beginning 90ies. More than 13 years later, the Fortran 90 standard was released by both ISO and ANSI in consecutive years. With FORTRAN 90, the fixed format standard was exchanged by a free format standard. In addition, many new features like modules, recur- sive procedures, derived data types and dynamic memory allocation made the language much more flexible. From Fortran 90 on, there has only been one major revision which basically introduced object-oriented programming features into the Fortran language in 2003. However, as object-oriented programming will not be needed and Fortran 90 is by far the more popular language, we will focus on the 1990 version in this book. 4 Chapter 2 – An Introduction to Fortran 90 2.1.2 Why to use Fortran Fortran is a general purpose, procedural, imperative, high-level programming language. In detail this means that (a) Fortran was not created for a special purpose like e.g. Matlab, Mathematica or Gauss were for efficiently dealing with matrices or solving mathematical problems, (b) Fortran code that will be used severaltimescanbestoredinfunctionsand subroutines that can be called from other program parts, (c) a Fortran program consists of statements that will be executed one after the other (i.e. a Fortran program starts with the first line and ends with the last), and (d) Fortran abstracts from the details of a computer, i.e. having the right compiler, Fortran code could be run on every computer independent of its hardware configuration and operating system. At this point our students usually ask "So, why to use Fortran? Why not a special pur- pose language or something more "fashionable" like Java?". Let us come up with some justifying points. First, special purpose languages might be relatively efficient in the spe- cific purpose they were created for, however, slow in other areas. Matlab, for example, is very good in working with matrices of regularorsparsenature.However,ifyouhave ever tried to run some do-loops in Matlab, you will know what we mean. Second, when it comes to the more "fashionable" languages like Java or C++, one has to always keep in mind that those languages are usually object-oriented and abundant. They are very good for creating software with Graphical User Interfaces, but not for running numerical maths code quickly and efficiently. As computational economics usually consists of at least 80% numerical methods, we need a programming language that is efficient in exe- cuting do-loops and if-statements, calling functions and subroutines and allows to per- manently store general code that is frequently used. Fortran is a language that matches all those features and not much more. The only real alternative we know would be C. There is no real reason why not to use C instead of Fortran, it’s just a matter of preference. Last but not least, Fortran has been used a lot by engineers, numerical mathematicians and computational economists during the 80ies and 90ies where a lot of optimizers and interpolation techniques were written. Fortunately, Fortran 90 is backward compatible with FORTRAN 77, i.e. all the code that is out there can be easily included in our Fortran programs. All in all, it seems reasonable for us to have chosen a language that matches all the fea- tures we need but does not come with any unnecessary extras that just make execution less efficient. 2.1.3 The way high-level programming languages work Low-level assembly languages that are basically used to program computers, micropro- cessors, etc. do not abstract from the computer’s instruction set architecture. Therefore, the syntax of assembly languages depends on the specific physical or virtual computer used. In addition, assembly languages are quite complicated and even a small programm 2.1. About Fortran in general 5 requires many lines of computer code. In opposite to that, high-level programming languages abstract from the system architec- ture and are therefore portable between different systems. As in all other languages, one has to learn the vocabulary, grammar, and punctuation called syntax of that language. However, compared to real languages, the syntax of a high-level language can be learned within some hours. In addition, the semantics, i.e. the meaning or interpretation of the different symbols you use, usually follows principles that can be comprehended by using pure logic. As high-level languages abstract from the computer’s instruction set architecture, one needs a compiler, sometimes also called interpreter, that interprets the statements given in the program and translates them into a computer’s native language, i.e. binary code. The way high-level programming works can be seen from Figure 2.1. First, the programmer Source Code Programmer Compilation Other Libraries Object Code Compiler Linkage Operating Executable (binary) System/ Hardware Figure 2.1: The way high-level compilers work has to write his source code in the respective high-level language and hand it over to the compiler. The compiler now proceeds in two steps. In the compilation step he interprets the source code and creates a so called object code file which consists of binary code. Binary code files usually have the suffix .obj. During this step, the compiler usually performs a syntax validation scan. If there are any syntactical errors, it produces error messages and stops the compilation process. In order to create an executable file, which has the suffix .exe in Microsoft® Windows, the compiler now links theobjectcodewithall other libraries that are needed to run the program, e.g. external numerical routines. The resulting executable can now be sent to the operating system which advises the hardware to do what exactly the programmer wants. 6 Chapter 2 – An Introduction to Fortran 90 2.1.4 Fortran Compilers for Windows® and Linux For beginners, we suggest to use the SilverFrost FTN95 compiler. You can download a free Personal Edition from http://www.silverfrost.com and install it on you com- puter by double-clicking on the downloaded file. The setup agent will guide you through the installation process. SilverFrost’s FTN95 compiler comes with a graphical user inter- face called Plato. You can open this program by double-clicking "Plato 3 IDE" in the "Start -> Programs -> Salford Software" menu. The user interface can be seen in Figure 2.2. Figure 2.2: The Plato user interface for the FTN95 compiler Below the main menu there are two lines of shortcut symbols, the first of which is nearly self-explanatory. The only thing that needs some explanation is the drop-down menu with the three possible execution modes for FTN95. The standard entry thereby is Check- Mate Win 32. CheckMate is a graphical debugger, the Debug mode is a simple console debugging mode. Using CheckMate or Debug and running into an error, the compiler will 2.1. About Fortran in general 7 give us detailed information about what happened and where exactly it occurred. In op- posite to that, Release minimizes the debug information in our programm which makes it run pretty quick. Note, however, that the Release mode should only be used, if the pro- gram is fully developed and free of bugs. Please only use the Win32 modes, as the .NET modes are only conceived for users that want to integrate the FTN95 compiler into a Mi- crosoft® .NET Framework. Using the .NET mode without having the compiler properly integrated into the framework can produce weird results.1 The text field and the three buttons on the right of the execution mode choice menu are used to search within a pro- gram or a file. The next two buttons increase and decrease the intent of code, respectively. The two buttons on the right of the intent buttons comment or uncomment some code lines. The last four buttons finally can be used to toggle bookmarks. In order to demonstrate the usage of the second line of shortcut symbols, we first have to write a small program. You can start a new program by creating a Free Format Fortran Source File via using the "File -> New" button and typing some program code.
Recommended publications
  • 7. Functions in PHP – II
    7. Functions in PHP – II Scope of variables in Function Scope of variable is the part of PHP script where the variable can be accessed or used. PHP supports three different scopes for a variable. These scopes are 1. Local 2. Global 3. Static A variable declared within the function has local scope. That means this variable is only used within the function body. This variable is not used outside the function. To demonstrate the concept, let us take an example. // local variable scope function localscope() { $var = 5; //local scope echo '<br> The value of $var inside the function is: '. $var; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $var inside the function is: '. $var; The output will be: The value of $var inside the function is: 5 ( ! ) Notice: Undefined variable: var in H:\wamp\www\PathshalaWAD\function\function localscope demo.php on line 12 Call Stack # Time Memory Function Location 1 0.0003 240416 {main}( ) ..\function localscope demo.php:0 The value of $var inside the function is: Page 1 of 7 If a variable is defined outside of the function, then the variable scope is global. By default, a global scope variable is only available to code that runs at global level. That means, it is not available inside a function. Following example demonstrate it. <?php //variable scope is global $globalscope = 20; // local variable scope function localscope() { echo '<br> The value of global scope variable is :'.$globalscope; } localscope(); // call the function // using $var outside the function will generate an error echo '<br> The value of $globalscope outside the function is: '.
    [Show full text]
  • B-Prolog User's Manual
    B-Prolog User's Manual (Version 8.1) Prolog, Agent, and Constraint Programming Neng-Fa Zhou Afany Software & CUNY & Kyutech Copyright c Afany Software, 1994-2014. Last updated February 23, 2014 Preface Welcome to B-Prolog, a versatile and efficient constraint logic programming (CLP) system. B-Prolog is being brought to you by Afany Software. The birth of CLP is a milestone in the history of programming languages. CLP combines two declarative programming paradigms: logic programming and constraint solving. The declarative nature has proven appealing in numerous ap- plications, including computer-aided design and verification, databases, software engineering, optimization, configuration, graphical user interfaces, and language processing. It greatly enhances the productivity of software development and soft- ware maintainability. In addition, because of the availability of efficient constraint- solving, memory management, and compilation techniques, CLP programs can be more efficient than their counterparts that are written in procedural languages. B-Prolog is a Prolog system with extensions for programming concurrency, constraints, and interactive graphics. The system is based on a significantly refined WAM [1], called TOAM Jr. [19] (a successor of TOAM [16]), which facilitates software emulation. In addition to a TOAM emulator with a garbage collector that is written in C, the system consists of a compiler and an interpreter that are written in Prolog, and a library of built-in predicates that are written in C and in Prolog. B-Prolog does not only accept standard-form Prolog programs, but also accepts matching clauses, in which the determinacy and input/output unifications are explicitly denoted. Matching clauses are compiled into more compact and faster code than standard-form clauses.
    [Show full text]
  • Chapter 21. Introduction to Fortran 90 Language Features
    http://www.nr.com or call 1-800-872-7423 (North America only), or send email to [email protected] (outside North Amer readable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, v Permission is granted for internet users to make one paper copy their own personal use. Further reproduction, or any copyin Copyright (C) 1986-1996 by Cambridge University Press. Programs Copyright (C) 1986-1996 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN FORTRAN 90: THE Art of PARALLEL Scientific Computing (ISBN 0-521-57439-0) Chapter 21. Introduction to Fortran 90 Language Features 21.0 Introduction Fortran 90 is in many respects a backwards-compatible modernization of the long-used (and much abused) Fortran 77 language, but it is also, in other respects, a new language for parallel programming on present and future multiprocessor machines. These twin design goals of the language sometimes add confusion to the process of becoming fluent in Fortran 90 programming. In a certain trivial sense, Fortran 90 is strictly backwards-compatible with Fortran 77. That is, any Fortran 90 compiler is supposed to be able to compile any legacy Fortran 77 code without error. The reason for terming this compatibility trivial, however, is that you have to tell the compiler (usually via a source file name ending in “.f”or“.for”) that it is dealing with a Fortran 77 file. If you instead try to pass off Fortran 77 code as native Fortran 90 (e.g., by naming the source file something ending in “.f90”) it will not always work correctly! It is best, therefore, to approach Fortran 90 as a new computer language, albeit one with a lot in common with Fortran 77.
    [Show full text]
  • Cobol Vs Standards and Conventions
    Number: 11.10 COBOL VS STANDARDS AND CONVENTIONS July 2005 Number: 11.10 Effective: 07/01/05 TABLE OF CONTENTS 1 INTRODUCTION .................................................................................................................................................. 1 1.1 PURPOSE .................................................................................................................................................. 1 1.2 SCOPE ...................................................................................................................................................... 1 1.3 APPLICABILITY ........................................................................................................................................... 2 1.4 MAINFRAME COMPUTER PROCESSING ....................................................................................................... 2 1.5 MAINFRAME PRODUCTION JOB MANAGEMENT ............................................................................................ 2 1.6 COMMENTS AND SUGGESTIONS ................................................................................................................. 3 2 COBOL DESIGN STANDARDS .......................................................................................................................... 3 2.1 IDENTIFICATION DIVISION .................................................................................................................. 4 2.1.1 PROGRAM-ID ..........................................................................................................................
    [Show full text]
  • Scope in Fortran 90
    Scope in Fortran 90 The scope of objects (variables, named constants, subprograms) within a program is the portion of the program in which the object is visible (can be use and, if it is a variable, modified). It is important to understand the scope of objects not only so that we know where to define an object we wish to use, but also what portion of a program unit is effected when, for example, a variable is changed, and, what errors might occur when using identifiers declared in other program sections. Objects declared in a program unit (a main program section, module, or external subprogram) are visible throughout that program unit, including any internal subprograms it hosts. Such objects are said to be global. Objects are not visible between program units. This is illustrated in Figure 1. Figure 1: The figure shows three program units. Main program unit Main is a host to the internal function F1. The module program unit Mod is a host to internal function F2. The external subroutine Sub hosts internal function F3. Objects declared inside a program unit are global; they are visible anywhere in the program unit including in any internal subprograms that it hosts. Objects in one program unit are not visible in another program unit, for example variable X and function F3 are not visible to the module program unit Mod. Objects in the module Mod can be imported to the main program section via the USE statement, see later in this section. Data declared in an internal subprogram is only visible to that subprogram; i.e.
    [Show full text]
  • Declare and Assign Global Variable Python
    Declare And Assign Global Variable Python Unstaid and porous Murdoch never requiring wherewith when Thaddus cuts his unessential. Differentiated and slicked Emanuel bituminize almost duly, though Percival localise his calices stylize. Is Normie defunctive when Jeff objurgates toxicologically? Programming and global variables in the code shows the respondent what happened above, but what is inheritance and local variables in? Once declared global variable assignment previously, assigning values from a variable from python variable from outside that might want. They are software, you will see a mortgage of armor in javascript. Learn about Python variables plus data types, you must cross a variable forward declaration. How like you indulge a copy of view object in Python? If you declare global and. All someone need is to ran the variable only thing outside the modules. Why most variables and variable declaration with the responses. Python global python creates an assignment statement not declared globally anywhere in programming both a declaration is teaching computers, assigning these solutions are quite cumbersome. How to present an insurgent in Python? Can assign new python. If we boast that the entered value is invalid, sometimes creating the variable first. Thus of python and assigned using the value globally accepted store data. Python and python on site is available in coding and check again declare global variables can refer to follow these variables are some examples. Specific manner where a grate is screwing with us. Global variable will be use it has the python and variables, including headers is a function depending on. Local variable declaration is assigned it by assigning the variable to declare global variable in this open in the caller since the value globally.
    [Show full text]
  • A Quick Reference to C Programming Language
    A Quick Reference to C Programming Language Structure of a C Program #include(stdio.h) /* include IO library */ #include... /* include other files */ #define.. /* define constants */ /* Declare global variables*/) (variable type)(variable list); /* Define program functions */ (type returned)(function name)(parameter list) (declaration of parameter types) { (declaration of local variables); (body of function code); } /* Define main function*/ main ((optional argc and argv arguments)) (optional declaration parameters) { (declaration of local variables); (body of main function code); } Comments Format: /*(body of comment) */ Example: /*This is a comment in C*/ Constant Declarations Format: #define(constant name)(constant value) Example: #define MAXIMUM 1000 Type Definitions Format: typedef(datatype)(symbolic name); Example: typedef int KILOGRAMS; Variables Declarations: Format: (variable type)(name 1)(name 2),...; Example: int firstnum, secondnum; char alpha; int firstarray[10]; int doublearray[2][5]; char firststring[1O]; Initializing: Format: (variable type)(name)=(value); Example: int firstnum=5; Assignments: Format: (name)=(value); Example: firstnum=5; Alpha='a'; Unions Declarations: Format: union(tag) {(type)(member name); (type)(member name); ... }(variable name); Example: union demotagname {int a; float b; }demovarname; Assignment: Format: (tag).(member name)=(value); demovarname.a=1; demovarname.b=4.6; Structures Declarations: Format: struct(tag) {(type)(variable); (type)(variable); ... }(variable list); Example: struct student {int
    [Show full text]
  • Chapter 5. Using Tcl/Tk
    The Almagest 5-1 Chapter 5. Using Tcl/Tk Authors: Edward A. Lee Other Contributors: Brian L. Evans Wei-Jen Huang Alan Kamas Kennard White 5.1 Introduction Tcl is an interpreted “tool command language” designed by John Ousterhout while at UC Berkeley. Tk is an associated X window toolkit. Both have been integrated into Ptolemy. Parts of the graphical user interface and all of the textual interpreter ptcl are designed using them. Several of the stars in the standard star library also use Tcl/Tk. This chapter explains how to use the most basic of these stars, TclScript, as well how to design such stars from scratch. It is possible to define very sophisticated, totally customized user interfaces using this mechanism. In this chapter, we assume the reader is familiar with the Tcl language. Documentation is provided along with the Ptolemy distribution in the $PTOLEMY/tcltk/itcl/man direc- tory in Unix man page format. HTML format documentation is available from the other.src tar file in $PTOLEMY/src/tcltk. Up-to-date documentation and software releases are available by on the SunScript web page at http://www.sunscript.com. There is also a newsgroup called comp.lang.tcl. This news group accumulates a list of frequently asked questions about Tcl which is available http://www.teraform.com/%7Elvirden/tcl-faq/. The principal use of Tcl/Tk in Ptolemy is to customize the user interface. Stars can be created that interact with the user in specialized ways, by creating customized displays or by soliciting graphical inputs. 5.2 Writing Tcl/Tk scripts for the TclScript star Several of the domains in Ptolemy have a star called TclScript.
    [Show full text]
  • A Tutorial Introduction to the Language B
    A TUTORIAL INTRODUCTION TO THE LANGUAGE B B. W. Kernighan Bell Laboratories Murray Hill, New Jersey 1. Introduction B is a new computer language designed and implemented at Murray Hill. It runs and is actively supported and documented on the H6070 TSS system at Murray Hill. B is particularly suited for non-numeric computations, typified by system programming. These usually involve many complex logical decisions, computations on integers and fields of words, especially charac- ters and bit strings, and no floating point. B programs for such operations are substantially easier to write and understand than GMAP programs. The generated code is quite good. Implementation of simple TSS subsystems is an especially good use for B. B is reminiscent of BCPL [2] , for those who can remember. The original design and implementation are the work of K. L. Thompson and D. M. Ritchie; their original 6070 version has been substantially improved by S. C. Johnson, who also wrote the runtime library. This memo is a tutorial to make learning B as painless as possible. Most of the features of the language are mentioned in passing, but only the most important are stressed. Users who would like the full story should consult A User’s Reference to B on MH-TSS, by S. C. Johnson [1], which should be read for details any- way. We will assume that the user is familiar with the mysteries of TSS, such as creating files, text editing, and the like, and has programmed in some language before. Throughout, the symbolism (->n) implies that a topic will be expanded upon in section n of this manual.
    [Show full text]
  • Quick Tips and Tricks: Perl Regular Expressions in SAS® Pratap S
    Paper 4005-2019 Quick Tips and Tricks: Perl Regular Expressions in SAS® Pratap S. Kunwar, Jinson Erinjeri, Emmes Corporation. ABSTRACT Programming with text strings or patterns in SAS® can be complicated without the knowledge of Perl regular expressions. Just knowing the basics of regular expressions (PRX functions) will sharpen anyone's programming skills. Having attended a few SAS conferences lately, we have noticed that there are few presentations on this topic and many programmers tend to avoid learning and applying the regular expressions. Also, many of them are not aware of the capabilities of these functions in SAS. In this presentation, we present quick tips on these expressions with various applications which will enable anyone learn this topic with ease. INTRODUCTION SAS has numerous character (string) functions which are very useful in manipulating character fields. Every SAS programmer is generally familiar with basic character functions such as SUBSTR, SCAN, STRIP, INDEX, UPCASE, LOWCASE, CAT, ANY, NOT, COMPARE, COMPBL, COMPRESS, FIND, TRANSLATE, TRANWRD etc. Though these common functions are very handy for simple string manipulations, they are not built for complex pattern matching and search-and-replace operations. Regular expressions (RegEx) are both flexible and powerful and are widely used in popular programming languages such as Perl, Python, JavaScript, PHP, .NET and many more for pattern matching and translating character strings. Regular expressions skills can be easily ported to other languages like SQL., However, unlike SQL, RegEx itself is not a programming language, but simply defines a search pattern that describes text. Learning regular expressions starts with understanding of character classes and metacharacters.
    [Show full text]
  • Cypress Declare Global Variable
    Cypress Declare Global Variable Sizy Wain fuddle: he brims his angoras capitally and contemplatively. Clerkliest and lowered Stefano Time-sharingetiolates her vendue Gordan revivifying never whigs restlessly so allowedly or radiotelegraphs or retrace any repellently, vanishers isaerially. Lindsay digressive? Lastly you can equally set in global cypress code to start cypress checks the test code is installed, so far it is anticipated to Issues with web page layout probably go there, while Firefox user interface issues belong in the Firefox product. The asynchronous nature of Cypress commands changes the trout we pass information between people, but the features are nearly there for us to his robust tests. PATH do you heal use those check where binaries are. The cypress does not declared. Any keyvalue you world in your Cypress configuration file cypressjson by default under the env key terms become an environment variable Learn fast about this. The variable that location of our hooks run cypress, and south america after this callback. Other people told be using the demo site at exact same course as launch; this can result in unexpected things happening. Examples and cypress are declared with variables using globals by enable are shown below outside links! A variable declared outside a function becomes GLOBAL A global variable has global scope All scripts and functions on a web page can. API exposes BLE interrupt notifications to the application which indicates a different species layer and became state transitions to the user from the current interrupt context. This indicates if those folder explicitly importing as above the globally installed correctly according to help you; the same options when it just as level and.
    [Show full text]
  • Automatic Handling of Global Variables for Multi-Threaded MPI Programs
    Automatic Handling of Global Variables for Multi-threaded MPI Programs Gengbin Zheng, Stas Negara, Celso L. Mendes, Laxmikant V. Kale´ Eduardo R. Rodrigues Department of Computer Science Institute of Informatics University of Illinois at Urbana-Champaign Federal University of Rio Grande do Sul Urbana, IL 61801, USA Porto Alegre, Brazil fgzheng,snegara2,cmendes,[email protected] [email protected] Abstract— necessary to privatize global and static variables to ensure Hybrid programming models, such as MPI combined with the thread-safety of an application. threads, are one of the most efficient ways to write parallel ap- In high-performance computing, one way to exploit multi- plications for current machines comprising multi-socket/multi- core nodes and an interconnection network. Global variables in core platforms is to adopt hybrid programming models that legacy MPI applications, however, present a challenge because combine MPI with threads, where different programming they may be accessed by multiple MPI threads simultaneously. models are used to address issues such as multiple threads Thus, transforming legacy MPI applications to be thread-safe per core, decreasing amount of memory per core, load in order to exploit multi-core architectures requires proper imbalance, etc. When porting legacy MPI applications to handling of global variables. In this paper, we present three approaches to eliminate these hybrid models that involve multiple threads, thread- global variables to ensure thread-safety for an MPI program. safety of the applications needs to be addressed again. These approaches include: (a) a compiler-based refactoring Global variables cause no problem with traditional MPI technique, using a Photran-based tool as an example, which implementations, since each process image contains a sep- automates the source-to-source transformation for programs arate instance of the variable.
    [Show full text]