You are on page 1of 24

Fortran Programming

Grey Gordon
Indiana University

Fall 2014

Brief History of Fortran

Origins
I

Dates back to 1957.

Life before Fortran: assembly code very fast but tedious.

FORmula TRANslator: readable code translated to assembly.

Focus from the start has been on speed.

Who uses Fortran today?


I

Scientists and engineers number crunchers

NOT vast majority of programmers who need GUIs not speed

Brief History of Fortran


FORTRAN 77 (F77)
I
I
I

Many fast libraries coded in F77. Ex., BLAS and LAPACK.


Matlab written in F77 originally (later translated to C).
Built to run on punchcards (fixed-source format).
FIND THE LARGEST NUMBER IN ABSOLUTE VALUE
IX = 1
DMAX = DABS ( DX (1))
IX = IX + INCX
DO 10 I = 2 , N
IF ( DABS ( DX ( IX )). LE . DMAX ) GO TO 5
IDAMAX = I
DMAX = DABS ( DX ( IX ))
5
IX = IX + INCX
10 CONTINUE
RETURN

NOTE: C is very similar to this.

Brief History of Fortran

Fortran 90/95 (F90) (the standard)


I

Major advance adding new features.

Added dynamic memory allocation, pointers, basic


object-oriented programming.

Built to run on modern computers (free-source format).

Fortran 95 was a slight revision that fixed a few problems.

Supports all F77 features but some are obsoleted like GOTO.

! Same as preceding code


dmax = maxval ( abs ( x ))

Brief History of Fortran

Fortran 2003 (F03)


I

Fairly well supported.

Latest Intel compiler supports all features now.

Large focus on interfacing with C.

Fortran 2008 (F08)


I

Intel compiler supports a fairly large number of features.

Some important features introduced like procedure pointers and


coarrays (a simple way to do distributed parallel computing).

Brief History of Fortran

Where to find help:


I

Very basic things: www.cs.mtu.edu/~shene/COURSES/


cs201/NOTES/fortran.html

Fortran manuals (Intel or gfortran)

Google

Other Fortran coders

Copyrights, wrongs, and plagiarism


You may use codes written by others if you cite their code.
I
I

If you do not cite their code, this is plagiarism.


If you begin with their code as a base, modify it, and do not
cite their code, this is plagiarism.

Because it is for education, you should be fine under fair usean


exception to copyright laws (that is, they probably wont sue you).
In general, later in life you need to be concerned with licenses.
Code is released under various licenses. Examples:
I
I
I
I
I
I

All rights reserved


BSD License
GNU GPL License
Public domain
Custom
Unspecified

Copyrights, wrongs, and plagiarism


Original code:
function [Z , Zprob ] = tauchen (N , mu , rho , sigma , m )
% Function TAUCHEN
%
% Purpose :
Finds a Markov chain whose sample paths
%
approximate those of the AR (1) process
%
z ( t +1) = (1 - rho )* mu + rho * z ( t ) + eps ( t +1)
%
where eps are normal with stddev sigma
%
% Format :
{Z , Zprob } = Tauchen (N , mu , rho , sigma , m )
%
% Input :
N
scalar , number of nodes for Z
%
mu
scalar , unconditional mean of process
%
rho
scalar
%
sigma
scalar , std . dev . of epsilons
%
m
max + - std . devs .
%
% Output :
Z
N *1 vector , nodes for Z
%
Zprob
N * N matrix , transition probabilities
%
%
Martin Floden
%
Fall 1996
%
%
This procedure is an implementation of George Tauchen ' s algorithm
%
described in Ec . Letters 20 (1986) 177 -181.
Z
Zprob
a
Z(N)
Z (1)
zstep
[...]

=
=
=
=
=
=

zeros (N ,1);
zeros (N , N );
(1 - rho )* mu ;
m * sqrt ( sigma ^2 / (1 - rho ^2));
-Z ( N );
( Z ( N ) - Z (1)) / ( N - 1);

Copyrights, wrongs, and plagiarism


New code with proper citation (fine):
function [Z , Zprob ] = tauchen (N , mu , rho , sigma , m )
% Function TAUCHEN
%
% Input :
N
scalar , number of nodes for Z
%
mu
scalar , unconditional mean of process
%
rho
scalar
%
sigma
scalar , std . dev . of epsilons
%
m
max + - std . devs .
%
% Output :
Z
N *1 vector , nodes for Z
%
Zprob
N * N matrix , transition probabilities
%
%
Originally by Martin Floden
%
Modified slightly by Grey Gordon
Z
Zprob
a
Z(N)
Z (1)
zstep
[...]

=
=
=
=
=
=

zeros (N ,1);
zeros (N , N );
(1 - rho )* mu ;
m * sqrt ( sigma ^2 / (1 - rho ^2));
-Z ( N );
( Z ( N ) - Z (1)) / ( N - 1);

Since this acknowledges the original author, even though there are
few modifications, this is fine.

Copyrights, wrongs, and plagiarism


New code without proper citation (VERY BAD):
function [Z , Zprob ] = tauchen (N , mu , rho , sigma , m )
% Function TAUCHEN
%
% Input :
N
number of points
%
mu
mean
%
rho
persistence
%
sigma
conditional stdev
%
m
coverage
%
% Output :
Z
nodes
%
Zprob
transition matrix
%
Z
= zeros (N ,1);
Zprob = zeros (N , N );
a
= (1 - rho )* mu ;
Z = linspace ( - m * sqrt ( sigma ^2 / (1 - rho ^2)) , ...
m * sqrt ( sigma ^2 / (1 - rho ^2)) , N );
[...]

Since this has no mention of the original author, even though it is


modified, even though it improves on the original code, this is
plagiarism.

Copyrights, wrongs, and plagiarism

When in doubt, cite!

Copyrights, wrongs, and plagiarism

Youll probably want to use the code you develop in this class later
in life. In that case, you need to be concerned about licenses.

Copyrights, wrongs, and plagiarism


Example of a nice license (LAPACK, emphasis added):
Copyright (c) 1992-2008 The University of Tennessee. All rights reserved.
COPYRIGHT
Additional copyrights may follow
HEADER
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer listed in this license in the documentation and/or other materials provided with the distribution.
- Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ... [truncated]

You can use LAPACK as much as you want (if you meet the
conditions).

Copyrights, wrongs, and plagiarism


The worst license I have ever seen (really a FAQ about the
Numerical Recipes license, emphasis added) :
When Do I Need a License? The Numerical Recipes book, and its electronic subscription version Numerical Recipes
Electronic, are sold as text and reference works, for reading and educational purposes. If you intend to use
Numerical Recipes code on a computer, you need a separate license. What Kinds of Licenses Are There? There are
two kinds of licenses. 1. With the purchase of a Numerical Recipes Code product, either a code download or a
Numerical Recipes Code CD-ROM, you automatically get a non-expiring Numerical Recipes Personal, Single-User
License that allows one individual to use the code on any number of computers.
2. With the purchase of a Numerical Recipes institutional subscription, you get a Numerical Recipes Institutional
Subscriber License that allows use of the code by any number of individuals on computers within a subscribers
fixed IP address range, during the term of the subscription.
See complete license terms for both license types here.
Can I Distribute Numerical Recipes Routines with My Application Bound invisibly into your executable .exe file?
Generally yes. As source code, linkable object libraries, or DLLs? Generally no. See more details here. Can a
Business Use Personal, Single-User Licenses? Yes, if each such license purchased is permanently assigned to a
specific individual before it is first used. Note, however, that the Personal, Single-User License may be assigned
only once, to a single individual. Thereafter it stays with that individual, whether or not he/she continues as an
employee. The single-user license is not a floating licenses or a license by the seat. Businesses needing greater
flexibility should purchase institutional subscriptions. What Else Comes with an Institutional Subscriber License?
For machines in the subscribers IP address range, institutional subscriptions include both unlimited access to
Numerical Recipes Code (and the license for its use), and also unlimited access to Numerical Recipes Electronic,
the electronic form of the Numerical Recipes book. The institutional subscription is generally the most
cost-effective way to make Numerical Recipes available to work groups, companies, and universities.

You should never use Numerical Recipes. Dont even look at it.

Programming

Now, back to the interesting stuff!

Comparison of Fortran and Matlab

Case sensitivity
1. Fortran is not case-sensitive: foo==FOO==fOo
2. Matlab is case-sensitive: foo/=FOO/=fOo

Comparison of Fortran and Matlab

Compiled vs Interpreted Languages


I

Matlab is an interpreted language.


I
I

What does B = sum(A) mean in Matlab?


The interpreter has to
I
I
I
I

Read the expression.


Check what A is currently (scalar? ND-array?).
Determine what sum() does for this type of argument.
Create space for B on the LHS.

This is in fact why loops are so slow.

Comparison of Fortran and Matlab

Compiled vs Interpreted Languages


I

Fortran is a compiled language.


I
I

What does B = sum(A) mean in Fortran?


The compiler determines before the program is run
I
I
I

What A is (scalar, ND-array?).


What sum() does.
Whether B is the right shape to fit sum(A).

Unfortunately, this requires more work for the programmer.

Comparison of Fortran and Matlab

Compiled vs Interpreted Languages


I

Advantages and Disadvantages


I
I

Compiled is much faster.


Compiled is much better at error-checking before the program
is run.
Interpreted is much more flexible.
I

Can implement dramatically different operations with just one


line of code.

Compiled is much more verbose (this is true of C as well as


Fortran).

Comparison of Fortran and Matlab

Typed vs Untyped Languages


I

Matlab is an untyped language.


I
I
I
I
I

What does B = sum(A) mean in Matlab?


Could mean A is a matrix and B is a vector.
Could also mean A is a vector and B is a scalar.
Moreover, A could be integers, or A could be decimals.
Implication: Matlab must check each time the line is reached.

Fortran is a strongly-typed language.


I
I
I

What does B = sum(A) mean in Fortran?


The programmer must declare A and B beforehand.
The compiler then knows before runtime, e.g. that A is an
integer matrix and B is an integer vector.

Comparison of Fortran and Matlab

Typed vs Untyped Languages


I
I

Matlab is now adding support for other classes (e.g. int64).


Advantages and Disadvantages
I
I
I

Similar to compiled vs interpeted.


Typed is much faster and safer better error-checking.
Untyped is slower, but more flexible and less verbose.
Object-oriented programming is easy.

When to use Fortran v Matlab

Basic principle: minimize total time


I

Time to run a program this will be faster in Fortran (maybe


by a factor of 10 or even 100)

Time to make a program this will be faster in Matlab (less


verbose, better debugging)

Total time depends on these two components.

When to use Fortran v Matlab

When to use Fortran.


I

If speed is critical.
I

For example if it has many loops that cannot be vectorized.

If your code is conceptually fairly straightforward.


I

O/w, it may be a good idea to prototype it in Matlab first.

When to use Matlab


I

If what you want to do is very complicated.

If what you want to do wont take long to run in Matlab.

When to use Fortran v Matlab


Rough categorization of types of problems:
I
I

Linearization Matlab
Estimation Fortran or Matlab
I

Probably use Mathematica or Matlab to do the symbolic math


and then generate Fortran code from it.

Higher-order perturbation Matlab or Fortran

Grid search in one-dimension Matlab or Fortran

Grid search in multiple-dimensions Fortran

Grid search in one-dimension (Business Cycle) Fortran or


Matlab

Grid search in multiple-dimensions (Business Cycle) Fortran

Projection methods with low-order polynomials Matlab

Projection methods with higher-order polynomials Fortran