Version of the Fortran programming language. The walking Dead. Fortran

  • Translation
I don't know what a programming language will look like in the year 2000, but I know that it will be called FORTRAN.
- Charles Anthony Richard Hoare, c. 1982

Fortran is rarely used in the industry today—it was ranked 28th on one list of popular languages. But Fortran is still main language for large scale simulations physical systems– that is, for things like astrophysical modeling of stars and galaxies (eg Flash), large-scale molecular dynamics, electron structure counting codes (SIESTA), climate models, etc. In the field of high-performance computing, of which large-scale numerical simulation is a subset, only two languages ​​are used today: C/C++ and “modern Fortran” (Fortran 90/95/03/08). Popular Open MPI libraries for parallelizing code have been developed for these two languages. In general, if you need quick code running on multiple processors, you only have two options. Modern Fortran has a feature called "coarray", which allows you to work with parallel programming directly in the language. Coarrays appeared in an extension to Fortran 95 and were later included in Fortran 2008.

The extensive use of Fortran by physicists often confuses computer scientists and others outside the field, who feel that Fortran is a historical anachronism.

I'd like to explain why Fortran is still useful. I don't encourage physics students to learn Fortran - since most of them will be doing research, they'd be better off learning C/C++ (or stick with Matlab/Octave/Python). I'd like to explain why Fortran is still in use, and argue that it's not just because physicists are "behind the curve" (although sometimes that is the case - last year I saw a physics student working with the code Fortran 77, but neither he nor his manager had heard anything about Fortran 90). Computer scientists should view the dominance of Fortran in numerical computing as a challenge.

Before we dive into the topic, I want to discuss some history because when people hear the word “Fortran,” they immediately think of punch cards and code with numbered lines. The first Fortran specification was written in 1954. Early Fortran (then its name was written in capital letters, FORTRAN), was, by modern standards, a hell of a language, but it was an incredible step forward from previous assembly programming. FORTRAN was often programmed using punched cards, as Professor Miriam Foreman of Stony Brook University recalls without pleasure. Fortran has had many versions, the most famous of which are the 66, 77, 90, 95, 03 and 08 standards.

It is often said that Fortran is still used today because of its speed. But is it the fastest? The site benchmarksgame.alioth.debian.org compares C and Fortran in several tests among many languages. In most cases, Fortran and C/C++ are the fastest. Darling Python programmers often 100 times slower, but this is par for the course for interpreted code. Python is not suitable for complex numerical calculations, but is good for others. Interestingly, C/C++ outperforms Fortran in all but two tests, although overall the results differ little. The tests where Fortran wins are the most “physical” - this is the simulation of an n-body system and the calculation of the spectrum. The results depend on the number of processor cores, for example Fortran is slightly behind C/C++ on a quad-core. The tests where Fortran lags far behind C/C++ spend most of their time reading and writing data, and Fortran is notoriously slow in this regard.

So, C/C++ is as fast as Fortran, and sometimes a little faster. We're wondering, "Why do physics professors keep telling their students to use Fortran instead of C/C++?"

Fortran has legacy code

Thanks to Fortran's long history, it is not surprising that mountains of physics code are written in it. Physicists try to minimize programming time, so if they find earlier code, they will use it. Even if the old code is unreadable, poorly documented and not the most efficient, it is more common to use the old tested one than to write new one. The job of physicists is not to write code; they are trying to understand the nature of reality. Professors have legacy code at their fingertips (often the code they wrote decades ago) and pass it on to their students. This saves them time and removes uncertainty from the bug fixing process.

Physics students find Fortran easier to learn than C/C++

I think Fortran is easier to learn than C/C++. Fortran 90 and C are very similar, but Fortran is easier to write. C is a relatively primitive language, so physicists who choose C/C++ are engaged in object-oriented programming. OOP can be useful, especially in large software projects, but it takes much longer to learn. You need to learn abstractions such as classes and inheritance. The OOP paradigm is very different from the procedural one used in Fortran. Fortran is based on a simple procedural paradigm, closer to what happens under the hood of a computer. When you optimize/vectorize code for speed, the procedural paradigm is easier to work with. Physicists usually understand how computers work and think in terms physical processes, for example, transferring data from disk to RAM, and from RAM to the processor cache. They differ from mathematicians, who prefer to think in terms of abstract functions and logic. This thinking is also different from object-oriented thinking. From my point of view, optimizing OOP code is more difficult than procedural code. Objects are very bulky structures compared to the data structures physicists prefer: arrays.

Ease first: working Fortran with arrays

Arrays, or matrices as physicists call them, are at the heart of all physics calculations. In Fortran 90+ you can find many features for working with them, similar to APL and Matlab/Octave. Arrays can be copied, multiplied by a scalar, multiplied among themselves in a very intuitive way:

A = B A = 3.24*B C = A*B B = exp(A) norm = sqrt(sum(A**2))
Here, A, B, C are arrays of some dimension (let's say 10x10x10). C = A*B gives us element-wise matrix multiplication if A and B are the same size. For matrix multiplication, use C = matmul(A,B). Almost all Fortran internal functions (Sin(), Exp(), Abs(), Floor(), etc.) take arrays as arguments, resulting in simple and clean code. There is simply no similar code in C/C++. In a basic C/C++ implementation, simply copying an array requires a run for loops over all elements or calling a library function. If you feed an array to the wrong library function in C, an error will occur. Having to use libraries instead of internal functions means that the resulting code will not be clean, portable, or easy to learn.

In Fortran, access to array elements works through the simple syntax A, whereas in C/C++ you need to write A[x][y][z]. Array elements start from 1, which corresponds to physicists’ ideas about matrices, and in C/C++ arrays the numbering starts from zero. Here are some more functions for working with arrays in Fortran.

A = (/ i , i = 1,100 /) B = A(1:100:10) C(10:) = B
First, vector A is created through an implied do loop, also known as an array constructor. Then a vector B is created, consisting of every 10th element of A, using a step of 10. Finally, array B is copied to array C, starting with the 10th element. Fortran supports array declarations with zero or negative indexes:

Double precision, dimension(-1:10) :: myArray
Negative index looks silly at first, but I've heard of their usefulness - for example, imagine this additional area to post any clarifications. Fortran also supports vector indexes. For example, you can transfer elements 1,5 and 7 from N x 1 array A to 3 x 1 array B:

Subscripts = (/ 1, 5, 7 /) B = A(subscripts)
Fortran supports array masks in all internal functions. For example, if we need to calculate the logarithm of all matrix elements greater than zero, we use:

Log_of_A = log(A, mask= A .gt. 0)
Or we can reset everything in one line negative elements array:

Where(my_array .lt. 0.0) my_array = 0.0
Fortran makes it easy to dynamically allocate and deallocate arrays. For example, to place a two-dimensional array:

Real, dimension(:,:), allocatable:: name_of_array allocate(name_of_array(xdim, ydim))
In C/C++ this requires the following notation:

Int **array; array = malloc(nrows * sizeof(double *)); for(i = 0; i< nrows; i++){ array[i] = malloc(ncolumns * sizeof(double)); }
To free an array in Fortran

Deallocate(name_of_array)
In C/C++ for this

For(i = 0; i< nrows; i++){ free(array[i]); } free(array);

Ease two: no need to worry about pointers and memory allocation

In languages ​​like C/C++, all variables are passed by value, with the exception of arrays, which are passed by reference. But in many cases, passing an array by value makes more sense. For example, let's say the data consists of the positions of 100 molecules at different time periods. We need to analyze the movement of one molecule. We take a slice of the array (subarray) corresponding to the coordinates of the atoms in this molecule and pass it to the function. In it we will deal with complex analysis of the transferred subarray. If we passed it by reference, the transferred data would not be located in memory in a row. Due to the nature of memory access, working with such an array would be slow. If we pass it by value, we will create a new array in memory, located in a row. To the delight of physicists, the compiler takes care of all the dirty work of optimizing memory.

In Fortran, variables are usually passed by reference rather than by value. Under the hood, the Fortran compiler automatically optimizes their transmission for efficiency. From a professor's point of view, the compiler should be trusted more than a student when it comes to memory optimization! As a result, physicists rarely use pointers, although they are available in Fortran-90+.

A few more examples of differences between Fortran and C

Fortran has several features to control the compiler when searching for errors and optimizations. Errors in the code can be caught at the compilation stage, and not at execution. For example, any variable can be declared as a parameter, that is, a constant.

Double precision, parameter:: hbar = 6.63e-34
If a parameter in the code changes, the compiler returns an error. In C this is called const

Double const hbar = 6.63e-34
The problem is that const real is different from simple real. If a function accepting real receives a const real, it will return an error. It's easy to imagine how this could lead to interoperability issues in your code.

Fortran also has an intent specification that tells the compiler whether the argument passed to a function is an input argument, an output argument, or both an input and an output argument. This helps the compiler optimize the code and increases its readability and reliability.

Fortran has other features that are used with different frequencies. For example, in Fortran 95 it is possible to declare functions with the pure modifier. Such a function has no side effects - it only changes its arguments and does not change global variables. A special case of such a function is the elemental function, which accepts and returns scalars. It is used to process array elements. Knowing that a function is pure or elemental allows the compiler to make additional optimizations, especially when parallelizing code.

What to expect in the future?

In scientific calculations, Fortran remains the main language, and is not going to disappear anytime soon. In a survey of visitors to the 2014 Supercomputing Convention using this language, 100% of them said that they were going to use it in the next 5 years. The survey also shows that 90% used a mixture of Fortran and C. Anticipating an increase in the mixing of these languages, the creators of the Fortran 2015 specification included more features for code interoperability. Fortran code is increasingly called from Python code. What computer scientists criticize the use of Fortran do not understand is that the language remains uniquely suited to what it was named after - FORmula TRANslation, that is, converting physical formulas into code. Many of them do not realize that the language is evolving and constantly includes new features.

Calling modern Fortran 90+ old is like calling old C++, due to the fact that C was developed in 1973. On the other hand, even the newest Fortran 2008 standard is backward compatible with Fortran 77 and most of Fortran 66. Therefore, language development is fraught with certain difficulties. Recently, researchers at MIT decided to overcome these difficulties by developing an HPC language from scratch called Julia, first released in 2012. Whether Julia will take the place of Fortran remains to be seen. In any case, I suspect that this will happen for a very long time.

Tags:

  • fortran
  • scientific programming
Add tags

I first heard about Fortran in early childhood from father. He said that in the 70s he had to stand in line for hours at almost the only computer in the university in order to run a primitive code using a punched card. I admit honestly, from then until recently (despite the technical education I received) I was in full confidence that Fortran remained somewhere far out there, in a world where information carriers are strange cardboard boxes with holes, and computers are so expensive, that are perceived as a real attraction.

Imagine my surprise when I learned that Fortran is not only still used somewhere, it is being developed, in demand and is still relevant. If you also believed until this moment that Fortran had long been dead, then here are a few for you: interesting facts why is he still walking?

Survived at least 10 updates

In fact, the Fortran you hear about from teachers at school or university was created between 1954 and 1957. It went down in history as the first fully implemented high-level language, made a small breakthrough in the IT world, but in essence it was not very convenient and functional. IBM began to “finish” it almost immediately; already in 1958, FORTRAN II appeared and, in parallel, FORTRAN III. But it acquired a more or less decent appearance only in the 70s, when fairly portable machines appeared, when a full-fledged IBM FORTRAN IV standard was developed, and FORTRAN 66 appeared with loops, labels, conditional statements, input/output commands and others by modern standards primitive capabilities.

The latest version appeared in 2010, its name is Fortran 2008 (as you can see, in the course of history, the name has ceased to be written exclusively in capital letters), the distinctive feature of which is all kinds of parallel calculations, which have a positive effect on both the speed of data processing and the size of the processed arrays . In addition, the release of Fortran 2015 is planned for 2018. From the announcement it follows that it will improve integration with C and also eliminate current shortcomings.

Among the 30 most popular programming languages

To date, 0.743% of requests in search engines Regarding programming languages, it is dedicated specifically to Fortran. To give you an idea of ​​how cool this is, just imagine that languages ​​like Lisp, Scala, Clojure, LabVIEW, Haskell, Rust, and VHDL are ranked lower.

Can work on Android (and more)

Over its long history, compilers for Fortana have been developed by companies such as IBM, Microsoft, Compaq, HP, Oracle, thanks to which today the language is compatible with Windows, Mac OS and Linux. Moreover, a convenient compiler application can now be taken with you thanks to the CCTools application for Android. You can run the compiler on your iPhone, but in this case you need to do a little magic.

Competes with MATLAB

So far, this text has not said the main thing, namely the scope of Fortran. So this is a language in demand in science and engineering, used in whole or in part for weather forecasting, oceanography, molecular dynamics, and seismological analysis. In general, this is a real “Data Science” language from the time when calculators first went on mass sale.

It is worth recognizing that Fortran owes part of its popularity to its heritage. Over the years, with virtually no competition, the language has acquired a huge base of clients, libraries and add-ons. In addition, each subsequent version of Fortran inevitably supports the previous ones. Therefore, a situation has arisen where there are no significant factors for scientists and engineers to abandon this alliance.

In fact, Fortran's main competitor today is MATLAB, which is more universal, more functional and convenient. However, MATLAB has strict limitations on the software used, is quite expensive and in most cases is simply unnecessary.

Has a relatively bright future

Of course, we cannot predict what will happen in 10-20 years, and how the IT world will change during this time. However, if you look at possible new competitors for Fortran (such as Go), their main drawback- universalization. That is, the creators of Fortran very quickly identified a target audience in the form of scientists, their opinions and wishes have priority. Therefore, it is difficult to imagine that tomorrow they will abandon their “special order” for the sake of some fashion trend. It is on this basis that we can say that another generation of Fortran is leaving boldly.

And then they'll just release a new version.

I was prompted to try to write my first post here, where vt4a2h suggests using C++ for learning. Yes, many copies have been broken on this topic.

I, like probably most schoolchildren in the vastness of our vast Motherland, began to comprehend the basics through blue screen, but not death, but Turbo Pascal 7.0. There was, of course, Basic, which I first encountered in preschool age on the Soviet computer "Electronics". Then it seemed like a strange text editor, because a computer through the eyes of a child was created for games. However, already at the institute I became acquainted with the Fortran language, having learned about it, I still wonder why it is not used for teaching.

Yes, many will say that the language is dead, does not correspond to modern realities, and textbooks with a title like in the picture only make you smile. I will try to explain why this language is so wonderful and why I recommend it as a first language. If you are interested, welcome to cat.

I believe that the basis for the basics of programming should be laid during school years, at least in high school. Even if in life the computer will only be used for typing text in Word or for communicating in in social networks, minimal knowledge of what an algorithm is and how to structure a sequence of actions to get the desired result will at least not harm the youngster in adulthood, but most likely will help to form a special mindset.

In order for computer science lessons to be a joy and not a nightmare, the student must understand what he is doing, how he is doing it and why it turns out this way and not otherwise. After all, in essence, you need to correctly convey information about the cycle and the conditional operator so that a person can write programs on their own. At the same time, the simpler the syntax of the language, the easier it is to understand the logic of writing code. If a person learns to compose correct algorithm, then to program in other languages, he will only need to learn the syntax of this language, and the basis will already be laid.

What is so special about Fortran?

Let us turn to the history of the creation of this language. It appeared in the distant 50s of the last century, when computers were still large, there were few programmers, and computer science was not taught at school, and was generally considered a pseudoscience. What was needed was a simple language that would help engineers and scientists “feed” formulas written on paper to computers, even through punched cards.

Hence the name of the language itself: For mula Tran slator or “formula translator”. Those. Initially, the language was aimed at people without special training, which means it had to be as simple as possible.

Well, the creators succeeded in simplicity. The classic first program looks like this:

Program hw write(*,*) "Hello, World!" end
The syntax is even a little simpler than Pascal, there is no need to put " at the end of the line ; " or " : " before the equal sign. Moreover, people with minimal knowledge of the English language can understand the meaning the simplest program won't be difficult.

Here I want to note that Fortran has several revisions of standards, the main ones being 77 and 90 (while maintaining continuity). 77 Fortran is really archaic, there is a limit on line length, and it is necessary to indent the beginning of the line, which can cause culture shock for a young programmer candidate. It’s not for nothing that programs written in Fortran 77 received the succinct name “Brezhnev Code” from the lips of my friend. Therefore, all my text refers to language standard 90 and newer.

As an example, I will give a code for calculating the sum of non-negative integers from 1 to n, entered from the keyboard, written by my graduate student while teaching her programming from scratch. It was where I experienced teaching Fortran as a first language. I hope that this was beneficial for her, and that my experiment was a success. She learned at least the basics in a couple of classes, the first of which was a lecture on language.

Program number implicit none ! Variables integer n,i,s ! Body of chisla s=0 write (*,*) "Enter n" read (*,*) n if (n.le.0) then write (*,*) "Negative or zero" else do i=1,n s =s+i end do write (*,*) "Sum=", s end if end
It is easy to see that the way we think is the way we write code. In principle, the student cannot experience any difficulties. The attentive reader will, of course, ask what is implicit none and two asterisks in parentheses separated by commas. implicit none tells us that we are explicitly specifying the type of the variables, whereas without this entry the compiler will guess the type itself. The first asterisk means that input and output occur on the screen, and the second indicates that the input and output format is detected automatically. Actually, the Fortran program looks no more complicated than the piece of code written above.

What about the software environment?

In schools, and in any government agencies, the question often arises about software, in particular about its licensing. Because money is not particularly allocated for these needs. At least in my time, this was a problem, maybe now the situation has changed for the better.

To write programs in Fortran Any will do text editor. If you want syntax highlighting, you can use Notepad++ (only supports standard 77 syntax) or SublimeText. We have written the program, how will we compile it? Everything is simple here, you can use the free GNU Fotran. If you plan to use it non-commercially, then you can also use a compiler from Intel, which is well optimized for processors of the same name and comes with the minimum required IDE. Those. The entry threshold is very preferential.

The best development environment for Fortran, according to many users, remains Compaq Visual Fortran 6.6, the latest version of which was released in the early 2000s. Why did it happen that an environment based on Visual Studio 6.0, which runs on Windows XP 32 bit at most without dancing with a tambourine, and has a limit on the memory used, has gained such popularity among Fortran users. The answer is shown in the figure below.

This is Compaq Array Visualizer, which is a very convenient tool for visualizing 1, 2 and 3-dimensional arrays during program debugging directly from the debugger. As they say, having tried it once, I eat it now. The fact is that Fortran is now used mainly in science (which will be discussed later), in particular in the field with which I am dealing, namely in atmospheric physics. When debugging programs, arrays represent various meteorological fields, such as temperature, pressure, wind speed. Finding an error in graphic fields is much easier than in a set of numbers, especially since you usually know what the field should look like, so obvious errors are cut off instantly.

Unfortunately, all developments on the compiler were transferred from Compaq to Intel. Intel initially supported Array Visualizer, however, those versions were already a pale reflection of the product from Compaq, working with them was not as convenient as before, but at least minimal functionality was maintained. Alas, Intel has stopped developing new versions of Array Visualizer, putting an end to this most convenient tool. That is why the bulk of the Fortran community writes programs and debugs them under Compaq Visual Fortran on Windows, and runs combat calculations on servers under Linux using Intel compilers. Intel, please hear the pleas of users, return a normal tool for visualizing arrays to your debugger!

Fortran's place in the modern world

And now we come to the very topic that usually causes a heated discussion with my colleagues who use Matlab, who claim that the rare language described in this post is good for nothing. Here I do not agree with them. The fact is that Fortran has historically been used in engineering or scientific calculations, and therefore over time it acquired a variety of ready-made libraries and program codes for solving a particular problem.

The code is literally passed down from generation to generation, and is also well documented. You can find many ready-made solutions equations of mathematical physics, linear algebra (here it should be noted the successful implementation of working with matrices), integral and differential equations and much, much more. It is probably difficult to find a problem in the field of physical and mathematical sciences for which an algorithm in Fortran would not be implemented. And if we take into account the excellent optimization of Intel compilers for Intel processors, support parallel computing on high-performance clusters, it becomes clear why this language takes a well-deserved first place in the scientific community. I think you can find a Fortran compiler installed on any supercomputer.

Most serious models, at least in the field of atmospheric physics, are written in Fortran. Yes, yes, the weather forecast, which everyone is interested in from time to time, is obtained through calculations of models written in this language. Moreover, the language is not stagnant, but is constantly improving. Thus, after the previously described standards 77 and 90, new editions 95, 2003, 2008 appeared, support for which has been introduced into current compilers. Latest versions Fortran somewhat refreshed the old time-tested language, providing support for the modern style, adding object-oriented programming, the absence of which was almost the most important trump card of opponents of this language. Moreover, The Portland Group has released PGI CUDA Fortran Compiler, which allows highly parallel calculations on video cards. Thus, the patient is more than alive, which means Fortran programmers are still in demand.

Instead of an afterword

And now I would like to return to the originally raised topic about learning to program, and try to briefly formulate the main advantages of Fortran when choosing it as a first language.
  • Fortran is very easy to learn, the syntax is understandable to an untrained person. Once you know the basics, it’s easy to relearn any other language.
  • A free set of tools allows you not to receive unnecessary questions from copyright holders.
  • The language is familiar to teachers, since it has existed for a long time, and our teachers are mainly representatives of the older generation.
  • Widely distributed throughout the world and is a treasure trove of all kinds of libraries.
  • Standardized, cross-platform and compatible with earlier revisions.
  • Useful for students of technical, and especially physics and mathematics majors, due to its focus on scientific and engineering calculations.
  • Relevant and in demand to this day.
So why not Fortran?

The Fortran programming language is used primarily for scientific computing. Invented in 1954, it oldest language high-level programming, followed by Lisp (1958), Algol (1958) and COBOL (1959). The number of scientific libraries written in Fortran and the creation of special translator-compilers allow the language to be used today. In addition, multiple calculators have been created for vectorization, coprocessors, parallelism, which intersperse this language for use in industrial production modern world.

John Backus, an IBM radio engineer, published papers in 1954 entitled "Preliminary Report", "Specifications for the IBM Matmal Transmula TRANslating System", which gave rise to the term FORTRAN. Then it took another two years of effort by the whole team, which he led, to write the first compiler for the Fortran programming language (25,000 lines for the IBM 704).

The name of the language was originally written in capital letters FORTRAN and was used to designate language versions up to Fortran 77, as opposed to free versions syntax starting with Fortran 90. In the Fortran 77 standard lower case are not part of the language, but most compilers support them in addition to the standard.

Today, the Fortran programming language is the dominant programming language used in engineering applications. Therefore, it is important that graduate engineers can read and modify Fortran code. From time to time, so-called experts predict that the language will lose its popularity and will soon cease to be used altogether.

These predictions always failed. Fortran is the most enduring computer programming language in history. One of the main reasons why the Fortran programming language has survived and will survive is inertia software. After a company has spent many resources and perhaps millions of dollars on a software product, it is unlikely that it will translate the software into another language.

The main advantage of Fortran is that it is standardized by the international bodies ANSI and ISO. Therefore, if a program is written in ANSI, it will run on any computer with a Fortran 77 compiler. This is important information. Thus, programs of the object-oriented programming language Fortran exist in different software devices.

Stages of creating a language platform:

  1. In 1954-1957, the first compiler was developed from scratch. In those days there were no "high level languages" (=HLL), most operating systems were simple, and the memory was small, something like 16 Kb. The first compiler ran on the IBM 704. This HLL language was much more efficient than assembly programming and very popular in its time.
  2. FORTRAN II was published in 1958. That same year, FORTRAN III was developed but never released into widespread production.
  3. In 1961, FORTRAN IV was created. It contained improvements such as the implementation of the COMMON and EQUIVALENCE statements.
  4. In 1962, an ASA committee began developing a standard for the object-oriented programming language Fortran. This allowed the seller to use it in every new computer. And this fact made it even more popular HLL, the language became available on Apple and TRS80 systems.
  5. In 1967, FORTRAN 66, the world's first HLL standard, was released. The publication of the standard meant that the language became more widely implemented than any other. By the mid-1970s, virtually every computer, mini, or mainframe was equipped with the standard FORTRAN 66 language. The language used if-statements, goto-statements, and spagethi programs. This type of structured programming became popular in the 60s and 70s.
  6. "Fortran" existed on punched cards in particular, with the FMS system, optimizing the layout of its sources until Fortran 90 introduced a "free" syntax. In it, the Fortran array code starts from the 7th column and should not exceed 72 thousand characters.

It should also be noted that before Fortran 90, spaces had no meaning between the 7th and 72nd column. Thus the cycle "DO I = 1.5" can also be written "DOI = 1.5". On the other hand, "DO I = 1.5" is equivalent to "DOI = 1.5".

Numerous industrial codes were written in Nastran, NAG and IMSL-Fortran library. Compatibility of new versions with previous ones is important. For this reason, Fortran 90 is fully compatible with Fortran 77. However, next versions the standard has already introduced incompatibilities.

The more advanced languages ​​Fortran 90 and Fortran 95 soon followed, updated to the current Fortran-2003 standard. Despite the fact that modern compilers work unlimitedly in all current versions of Windows and even support 64-bit processors. Meanwhile, manufacturers have recognized the trend of the times and are offering compilers for Linux in the form of the object-oriented programming language Actor Fortran.

Prerequisites for using a programming language

It must be understood that Fortran is still a widely used programming language and is mainly used in the field of discovery. Classic applications, for example in physics or engineering, where extensive and complex mathematical calculations. They are very useful due to the extensive mathematical libraries that exist for different compilers. To sum up, we can say that today Fortran language is still used for a number of reasons:

  • Availability of numerous functional libraries developed over many years.
  • Availability of software in Fortran, which requires very important resources for development when switching to another language is considered too costly.
  • Availability of powerful compilers with built-in Fortran functions that produce very fast executable files.
  • The language is more accessible to an inventor who has not had a specialized computer course.

Many science programs are now written in C and C++, with compilers available on most machines. Other compiled languages ​​are sometimes used for scientific computing, and especially for programs such as Scilab or Matlab. The latter also include the BLAS and LAPACK libraries developed in Fortran programming. Matlab was originally a Fortran program distributed to universities and research centers.

Although Tom Lahey is now the "only" general compiler, Lahey Computer Systems continues to be used by many programmers. Lahey has been working with Fujitsu for several years, Lahey focusing on the Fortran parser and Fujitsu on the code generator. The current Compiler Suite for Windows is called Lahey Fujitsu Fortran 95 (LF95) and is available in different versions, some of which also integrate with Visual Studio .NET 2003.

There is also an inexpensive version of LF95 Express without its own IDE. The current version is 7.1. on Linux is called by the Lahey/Fujitsu Fortran 95 v6.2 compiler for Linux and is available in two different versions. For example, the Pro version includes OpenMP v2.0 compatibility, a simple Winteracter Starter Kit graphics engine, a math library, and scientific library Fujitsu 2 routines.

Another manufacturer is Absoft. Compilers and C++ exist not only for Windows and Linux, but also for OS X on the Macintosh. These compilers are of interest to developers who need or want to support all three platforms. Unfortunately, Absoft differentiates between 32-bit and 64-bit versions for Linux, currently using version 10.0 of Fortran 95 for 64-bit Linux.

Relatively new to the market is the EKOPath Compiler Suite. This consists of C++ compilers and a Fortran development environment for Linux, which are also available separately and are mainly aimed at 64-bit AMDusers. It also runs on Intel EM64T. Microsoft also once tried to find a "cheap market" for Fortran and introduced the Microsoft Powerstation to the market.

The market may have been too small for the software giant, but Digital took over some of the code in 1997 and used its experience with the Digital Unix and OpenVMS compilers. This was the birth of the still very successful Digital Visual Fortran. At some point Digital then moved to Compaq, the compiler was developed to the current version of Compaq Visual Fortran (CVF) v6.6.

In addition to "normal" 32-bit platforms, there are various 64-bit compilers, for example for Intel Itanium and Intel EM64T. Although they are not "urgent" for the scope of supply, they are available for free download via web system Intel support Premier.

After a one-time, somewhat cumbersome registration, you can use it for a year, with new updates every few weeks. Even older versions will remain available.

A Fortran program is a sequence of lines of text. The text must follow a specific syntax. For example: a circle of radius r, area c.

This program reads the real radius and determines the area of ​​a circle with radius r:

"Radius r:"read (*, *) r;

area = 3.14159 * r * r;

write (*, *) "Area =";

Lines starting with "C" are comments and have no purpose other than to make the program more readable for people. Initially, all Fortran programs were written in capital letters. Most programmers now write lowercase because it's more legible.

A Fortran program typically consists of a main program or driver and several subroutines, procedures, or subroutines. Main program structure:

  • the name of the program;
  • declarations;
  • statements;
  • stop;
  • end.

Italics should not be taken as literal text, but rather as a general description. The stop statement is optional and may seem unnecessary since the program will stop when it reaches the end anyway, but it is recommended to always end a program with a stop statement to emphasize that the flow of execution is being terminated.

Column position rules

Fortran 77 is not a free format language, but has a very strict set of rules for formatting source code. Most important rules are the rules for the arrangement of columns:

  • Col. 1: Blank or “c” or “*” for comments.
  • Col. 2-5: operator mark.
  • Col. 6: continuation of the previous line.
  • Col. 7-72: statement.
  • Col. 73- 80: Sequence number.

A Fortran line beginning with the letter "c" or an asterisk in the first column is a comment. Comments can appear anywhere in a program. Well written, they are critical to the readability of a program. Commercial codes Fortran files often contain about 50% comments. You may also encounter programs that use Exclamation point(!). This is very non-standard in Fortran 77, but is allowed in Fortran 90.

The exclamation point can appear anywhere on a line. Sometimes a statement does not fit on one line, then you can break the statement into two or more lines and use a continuation sign in position.

  1. C23456789 - This demonstrates the position of the column.
  2. "C" - the next statement goes through two areas physical lines.
  3. Area = 3.14159265358979+ * r * r.

Empty spaces are ignored starting with Fortran 77. Therefore, if you remove all the spaces in Fortran 77, the program is still syntactically correct, although it is almost unreadable to the operators.

Variable names in Fortran consist of 1-6 characters, chosen from letters a-z and numbers 0-9. The first character must be a letter. Fortran 90 allows variable names of arbitrary length. Fortran 77 does not distinguish between upper and lower case, in fact it assumes all input is upper case. However, almost all F 77 compilers will accept lowercase letters. Each variable must be defined in a declaration. This sets the type of the variable. The most common variable lists are:

  • integer;
  • real;
  • double precision;
  • complex;
  • logical;
  • character.

The list of variables must consist of names separated by commas. Each variable must be declared exactly once. If a variable is not declared, F 77 uses a set of implicit rules to establish the type. This means that all variables starting with the letters "in" are integers, and all others are real numbers. Many older F 77 programs use these implicit rules, but programmers should not do so because the likelihood of program errors increases dramatically if they declare variables inconsistently.

Fortran 77 has only one type for integer variables. Integers are typically stored as 32-bit (4 byte) variables. Therefore, all integer variables must take values ​​in the range [-m, m], where m is approximately 2 * 10 9.

F 77 has two different types for floating point variables, called real double precision. Some numerical calculations require very high precision, and double precision should be used. Usually the real one is a 4-byte variable, and double precision- 8 bytes, but it depends on the machine.

Non-standard versions of Fortran use real*8 syntax to refer to 8-byte floating point variables. Some constants appear many times in a program. Therefore, it is advisable to define them only once, at the beginning of the program. The parameter operator is used for this. It also makes programs more readable. For example, a program for the area of ​​a circle should be written like this.

Parameter operator syntax (name = constant, ..., name = constant). Rules for the parameter operator:

  1. A "variable" defined in a parameter statement is not a variable, but a constant whose value can never change.
  2. "Variable" can display at most one parameter statement.
  3. The operator parameter must come before the first executable operator

Some good reasons to use a parameter - helps reduce typos, easy to change a constant that appears many times in a program.

Boolean expressions can only have the value.TRUE. or.FALSE. and can be formed by comparison using relational operators.

You cannot use characters such as "<» или «=» для сравнения в F 77, но можно использовать правильную двухбуквенную аббревиатуру, заключенную точками. Однако такие символы разрешены в Fortran 90.

Logical expressions can be combined with the logical operators “AND”, “OR”, “NOT”, which have obvious meaning. Truth values ​​can be stored in boolean variables. The assignment is similar to the arithmetic assignment.

Example: logical a, ba = .TRUE.b = a .AND. 3.LT. 5/2

The order of priority is very important. The rule is that arithmetic expressions are evaluated first, then relational operators, and finally logical operators. Therefore, b will be assigned .FALSE. In the example above, boolean variables are rarely used in Fortran, but they are often used in conditional statements such as the "if" statement.

Constant and purpose

The simplest form of an expression is a constant. There are 6 types of constants corresponding to 6 data types. Here are some integer constants: 10-10032767+15

Real constants: 1.0-0.252.0E63.333E-1.

E-notation means to multiply the constant by 10 raised to the power following the "E". Therefore, 2.0E6 is two million, and 3.333E-1 is approximately one third. For constants that are larger than the largest actually allowed, or that require high precision, double precision should be used. The notation is the same as for real constants, except that "E" is replaced by "D".

Example:2.0D-11D99.

Here 2.0D-1 is double precision with one fifth, while 1D99 is one followed by 99 zeros.

The next type is complex constants. They are denoted by a pair of constants (integer or real), separated by a comma and enclosed in parentheses.

Examples are: (2, -3)(1,9,9E-1). The first number denotes the real part, and the second the imaginary part.

The fifth type is logical constants. They can only have one of two meanings:

Please note that dots containing letters are required to be written.

The last type is character constants. They are most often used as an array of characters called a string. They consist of an arbitrary sequence of characters enclosed in apostrophes (single quotes):

"Anything goes!"

"It's a nice day"

String and character constants are case sensitive. The problem arises if you want to have a real apostrophe in the line itself. In this case, you need to double the apostrophe: "It" "s a nice day", which means "What a wonderful day"

Conditional statements are important components of any programming language. The most common of these statements in Fortran is the "if" statement, which actually has several forms.

The simplest is the logical expression “if” in the Fortran description: if (logical expression) executable statement.

This should be written on one line, for example when determining the absolute value of x:

if (x .LT. 0) x = -x

If more than one statement is to be executed in an "if", then the following syntax should be used: if (logical expression) thenstatementsendif.

Flow of execution from top to bottom. Conditional expressions are evaluated sequentially until a true value is found. The appropriate code is then executed and the control moves to the next statement after the end "if".

If statements can be nested multiple levels. To ensure readability, it is important to use proper indentation. Here's an example:

if (x .GT. 0) thenif (x .GE. y) thenwrite(*,*) "x is positive and x >= y"elsewrite(*,*) "x is positive but x< y"endifelseif (x .LT. 0) thenwrite(*,*) "x is negative"elsewrite(*,*) "x is zero"endif

Programmers should avoid nesting many levels of "if" statements as it will be difficult to follow.

You can use any Unix workstation with an F 77 compiler. Experienced programmers recommend using either Sun or Dec.

A Fortran program consists of plain text that follows certain syntax rules. This is called source code. Programmers use an editor to write source code. The most common editors on Unix are emacs and vi, but they can be a bit complex for novice users. You can use a simpler editor such as xedit, which runs under X windows.

Once a Fortran program is written, it is saved in a file with a “.f” or “.for” extension and the program is converted into machine-readable form. This is done using a special program called a compiler. The Fortran 77 compiler is commonly called f77. The compilation output is given the somewhat cryptic name "a.out" by default, but you can choose a different name if needed. To run the program, simply enter the name of the executable file, for example, "a.out". The compiler translates the source code into object code, and the linker or loader translates it into an executable file. As you can see, this procedure is not at all complicated and is accessible to any user.

Simulation is one of the most commonly used manufacturing methods and other systems found in modern factories. Most simulation models are built using the object-oriented programming language Actor Fortran, or a simulation software package written in a traditional language. These tools have their limitations. Object-oriented technology has seen increasing adoption in many fields and promises a more flexible and efficient approach to modeling business systems.

Simula Fortran programming is compared to a conventional scientific programming language called FORTRAN. A typical military simulation model is programmed in both SIMULA and FORTRAN. The SIMULA program was 24% shorter than the FORTRAN version.

The SIMULA version is also simpler and gives a better picture of the model being simulated. On the other hand, the execution time for production runs is 64% faster with the object-oriented programming language Simula Fortran. Weighing the pros and cons shows that SIMULA will be an increasingly profitable software, with higher personnel costs and lower computer costs.

CUDA shows how high-performance application developers can harness the power of GPUs using Fortran, a common language for scientific computing and supercomputer performance testing. The authors do not assume any prior parallel computing experience and cover only the basics as well as best practices. The computing efficiency of GPUs using CUDA Fortran is enabled by the target GPU architecture.

CUDA Fortran for Scientists and Engineers will identify computationally intensive parts of the code and modify the code for data management, parallelism, and performance optimization. All this is done in Fortran, without the need to rewrite the program into another language. Each concept is illustrated with actual examples so you can immediately evaluate the code's performance.

Perhaps one day the global corporation will “finally globalize” and decide that Fortran is no longer needed, but not now. Thanks to the current capabilities of modern Fortran, many programmers and scientists see it as the future. In addition, there are enough manufacturers in the world who live by developing modern compilers and make good money from this process.

Years.) The name Fortran is an abbreviation for FOR mula TRAN slator, that is, a formula translator. Fortran is widely used primarily for scientific and engineering computing. One of the advantages of modern Fortran is the large number of programs and subroutine libraries written in it (see, for example, Netlib Repository). Among scientists, for example, there is a saying that any mathematical problem already has a solution in Fortran, and, indeed, among thousands of Fortran packages you can find a package for multiplication, a package for solving complex integral equations, and many, many others. A number of such packages have been created over the decades and are popular (mainly in the scientific community) to this day.

Most of these libraries are actually the property of humanity: they are available in source code, well documented, debugged and very effective. Therefore, it is expensive to change, let alone rewrite them in other programming languages, despite the fact that attempts are regularly made to automatically convert FORTRAN code into modern programming languages.

Modern Fortran (Fortran 95 and Fortran 2003) has acquired the features necessary for efficient programming for new computing architectures; allows the use of modern programming technologies, in particular .

Standards

Fortran is a highly standardized language, which is why it is easily portable to various platforms. There are several international language standards:

  • FORTRAN IV(aka - FORTRAN 66) (1966)
  • FORTRAN 77 (1978)
    Many improvements: text data type and functions for processing it, block statements IF, ELSE IF, ELSE, END IF, INCLUDE statement, etc.
  • Fortran 90 (1991)
    The language standard has been significantly revised. A free format for writing code has been introduced. Additional descriptions have appeared for IMPLICIT NONE, TYPE, ALLOCATABLE, POINTER, TARGET, NAMELIST; control structures DO ... END DO, DO WHILE, CYCLE, SELECT CASE, WHERE; working with dynamic memory (ALLOCATE, DEALLOCATE, NULLIFY); software components MODULE, PRIVATE, PUBLIC, CONTAINS, INTERFACE, USE, INTENT. New built-in functions have appeared, primarily for working with arrays.
    Elements appeared in the language.
    A separate list of obsolete language features that are intended to be removed in the future has been announced.
  • Fortran 95 (1997)
    Correction of the previous standard.
  • Fortran 2003 (2004)
    Further development of language support. Interaction with the operating system.

Compilers

Features and structure of the program

Fortran has a fairly large set of built-in mathematical functions and supports working with integer, real and complex numbers of high precision. The expressive means of the language were initially very poor, since Fortran was one of the first high-level languages. Subsequently, many lexical structures characteristic of structural, functional and even object-oriented programming were added to Fortran.

The program structure was initially oriented towards input from

and had a number of properties convenient specifically for this case. Thus, the 1st column served to mark the text as a comment (with the symbol C), from 1st to 5th was the label area, and from 7th to 72nd was the actual text of the operator or comment. Columns 73 to 80 could be used to number cards (to restore a randomly scattered deck) or for a brief comment; they were ignored by the translator. If the operator's text did not fit into the allotted space (from the 7th to 72nd column), a continuation sign was placed in the 6th column of the next card, and then the operator continued on it. It was impossible to place two or more on one line (map). When punch cards became a thing of history, these advantages turned into serious inconveniences.

That is why, in the Fortran standard, starting with Fortran 90, in addition to the fixed format of the source text, a free format appeared, which does not regulate line positions, and also allows you to write more than one operator per line. The introduction of a free format has made it possible to create code that is as clear as code created using other modern programming languages ​​such as or .

A kind of “calling card” of the old Fortran is the huge number of labels that were used both in unconditional jump operators and in loop operators, and in FORMAT format input/output description operators. The large number of labels and GOTO statements often made Fortran programs difficult to understand.

It was this negative experience that became the reason why in a number of modern programming languages ​​(for example, ) labels and associated unconditional jump operators are completely absent.

However, modern Fortran gets rid of the excess of labels by introducing operators such as DO ... END DO, DO WHILE, SELECT CASE

Also, the positive features of modern Fortran include a large number of built-in operations with arrays and flexible support for arrays with unusual indexing. Example:

Real,dimension(:,:) :: V ... allocate(V(-2:2,0:10)) ! Allocate memory for an array whose indexes can! vary from -2 to 2 (first index) ! and from 0 to 10 - the second... V(2,2:3)=V(-1:0,1) ! Rotate a piece of the array write(*,*)V(1,:) ! Print all elements of array V whose first index is 1. deallocate(V)

Example program

Program "Hello, World!"

Fixed format (spaces in line positions 1 to 6 are marked with “ˆ” characters):

^^^^^^PROGRAM hello ^^^^^PRINT*, "Hello, World!" ^^^^^^END

Free format:

Program hello print *, "Hello, World!" end

Notes.

  • The PROGRAM statement is optional. Strictly speaking, the only required statement in a Fortran program is the END statement.
  • The choice of uppercase or lowercase letters for writing program statements is arbitrary. From the point of view of modern Fortran language standards, the set of uppercase letters and the set of lowercase letters coincide when writing language operators.