Difference between revisions of "Fortran1"

From SourceWiki
Jump to navigation Jump to search
Line 65: Line 65:
 
Although this has all been fairly painless, we have made a very significant step--we are now editing, compiling and running Fortran programs.  All the rest is basically just details!:)
 
Although this has all been fairly painless, we have made a very significant step--we are now editing, compiling and running Fortran programs.  All the rest is basically just details!:)
  
==Baskets and the Types of Things==
+
==Containers and the Types of Things==
  
 
As fun as "hello, world" was, let's spice things up a little.  For instance, let's introduce some variables.  Fortran90 has several types of built-in, or '''intrinsic''', variables.  Take a look in '''intrinsic_types.f90''':
 
As fun as "hello, world" was, let's spice things up a little.  For instance, let's introduce some variables.  Fortran90 has several types of built-in, or '''intrinsic''', variables.  Take a look in '''intrinsic_types.f90''':

Revision as of 10:31, 1 February 2008


Fortran1: The Basics

We'll forge our path through the verdant garden of Fortran90 using a number of examples. To get your copy of these examples, from the version control repository, login to your favourite linux machine (perhaps dylan), and type:

svn co http://source.ggy.bris.ac.uk/subversion/fortran1/trunk --username=guest ./fortran1

hello, world

Without further ado, and in-keeping with the most venerable of traditions, let's meet our first example--"hello, world":

cd fortran1/examples/example1

compile it by typing:

make

and run it by typing:

./hello_world.exe

Bingo! You've just compiled and run, perhaps your first, Fortran90 program. Hurrah! we're on our way:) Everybody whoop! Yeehah!

OK, OK...you'd better reign in your excitement. This is serious you know!:)

Enough of the magic, let's take a look inside the source code file. Open-up hello_world.f90, using cat, less, more or your favourite text editor, and you'll see:

!
! This is a comment line.
! Below is a simple 'hello, world' program written in Fortran90.
! It illustrates creating a main 'program' unit together
! with good habits, such as using 'implicit none' and comments.
!
program hello_world
  implicit none
  write(*,*)  "hello, world"
end program hello_world

We have:

  1. some comment lines, giving us a helpful narrative
  2. the start of the main program unit
  3. the implicit none statement (more of that in the next section, but suffice to say, every well dressed Fortran program should have one)
  4. a write statement, printing our greeting to the screen
  5. and last, but not least, the end of the main program.

We'll be using make to compile all our example programs, so you won't have to worry about that side of things. (If you'd like to know more about make, you can take a look at our course on make, presented in a very similar style to this here excursion into Fortran90.)

This is all pretty straight forward, right? Open-up your text editor and try changing the greeting, just for the heck of it. Retype make and re-run it. We'll adopt a similar strategy for all the other examples we'll meet. If you ever want to get back to the original version of a program, just type:

svn revert

Although this has all been fairly painless, we have made a very significant step--we are now editing, compiling and running Fortran programs. All the rest is basically just details!:)

Containers and the Types of Things

As fun as "hello, world" was, let's spice things up a little. For instance, let's introduce some variables. Fortran90 has several types of built-in, or intrinsic, variables. Take a look in intrinsic_types.f90:

  character         :: sex       ! a letter e.g. 'm' or 'f'
  character(len=12) :: name      ! a string
  logical           :: wed       ! married?
  integer           :: numBooks  ! must be a whole number
  real              :: height    ! e.g. 1.83 m (good include units in comment)
  complex           :: z         ! real and imaginary parts

These suffice for a great many programs. The above are all single entities. We'll meet arrays things in a couple of examples time. In Fortran2, we'll also meet user-defined types. These allow us to group instances of intrinsic types together forming new kinds of thing--new types. User-defined types are the bees knees and can make programs much easier to work with. We'll leave the details to that later course, however.

The above snippet shows some variable declarations, along with a helpful comment. It's good practice to comment your declarations as a programmer new to your code (or even yourself in a month or so's time) can have a hard time figuring out what is supposed to be stored in that variable named xbNew, or z2. Oh, while we're at it, it's also good practice to give your variables meaningful names, even if they are long. Trust me, a bit more typing now, perhaps, but a lot less head-scratching later!

We can also give variables an initial value when we declare them:

  character         :: nucleotide = 'A'            ! DNA has A,C,G & T
  character(len=50) :: infile = 'yourData.nc', outfile = "myData.nc"
  logical           :: initialised = .true.        ! or .false.
  real              :: solConst       = 1.37       ! Solar 'constant' in kW/m^2
  complex           :: sqrtMinusOne = (-1.0, 0.0)  ! sqrt(-1)

Fortran90 also allows us to gives variables certain attributes, for example:

  real,parameter    :: pi = 3.14159  ! a fixed constant
  real(kind=8)      :: totPrecip     ! this is preferred to 'double precision'

The parameter attribute tells you, me and Fortran that pi is a constant. It's fixed and it's a compile-time error if we try to change it. This is a good thing, since it can catch nasty bugs that can creep in if we do that kind of thing. Assigning parameter attributes to quantities we know are constant is an example of defensive programming, or bug avoidance!

By default reals in Fortran are represented using 4 bytes of memory. The addition of (kind=8) gives us an 8-byte real, often referred to a double precision real. Fortran does have a double precision type, but the kind attribute is preferred. (Many compilers also support the promotion of all default, 4-byte reals and integers in your program through flags, typically names -r8 and -i8, respectively.) Double precision can be useful as accumulators, since they can help to avoid rounding errors.

The remaining part of the program illustrates some pitfalls--beware!:

  • integer division and it's truncation
  • casting as a solution to mismatched types
  • (integer) overflow
  • (real number) underflow

Have a play with the program. Compile it and run it by typing:

make
./types.exe

Now modify the program (remembering "svn revert" if you make a mess). Try giving values to various types and also using some operators such as:

  • arithmetic: +, -, /, ** (exponentiation)
  • functions: sin, cos, floor
  • logic: .and., .or., .not., .eqv., .neqv.
  • and many more...

About that mysterious intent none which we keep seeing at the start of our programs. Let me tell you a story. Once upon a time, the kings and queens of the garden of Fortran, being a generous and well meaning bunch, decided to save the programmers the bother of specifying the type of their variables. "Don't bother!", they said, "just be sure to give 'em" appropriate names, and well sort out the rest. "Thank you very much", said the programmers, and it was decreed that the names of integers should start with the letters i, j, k, l, m, or n, and the names of reals would start with the other letters. Anyhow, this all seemed like a great wheeze and everybody was very happy. This lasted for a while, but after time, people forgot how to name things and it all got rather messy. Integers became reals, reals became integers and before they knew it, the programmers had BUGS all over the place! Boo. The kings and queens conferred on the matter and they realised that they had made a grave error in the gift of implicit typing. However, they couldn't undo what they had done. Instead, they had to persuade the programmers to give it up voluntarily. "Anything, anything!", they pleaded "to get rid of these BUGS!", and so it passed that every good programmer agreed to put implicit none at the top of every program they write.

If, Do, Select and Other Ways to Control the Flow

Not one, Many!

If Things get Hectic, Outsource!

You can Have That, and I'll Have This