Stefano Borini - 2011
Quick Fortran round up
Stefano Borini - 2011
Quick Fortran round up
Fortran is a programming language with the following characteristics
Imperativesequences of commands for the computer to perform.Static typedYou must declare the type of variables.Type checking is done when you compile, not when you run.Type is associated with the “container” (variable), not with the value that is contained.Strongly typedAutomatic conversion between different types is restricted(e.g. the string “37” and the number 37 are different)
Fortran is a compiled language
Fortran source code (.f90)
Object code (.o)
Module code (.mod)
Executable
Libraries(static .a)(dynamic .so/.dyld)
Compilation
Linking
Preprocessor
Fortran source code (.?)
Fortran Syntax: main program
program helloWorldwrite(*,*) “hello world”end program
stefanos-imac:~ borini$ gfortran hello.f90 -o hellostefanos-imac:~ borini$ ./hello hello worldstefanos-imac:~ borini$
Fortran Syntax: variables
program Varsimplicit noneinteger :: counterreal :: chargecharacter(len=128) :: namecomplex :: pointlogical :: isReadablecounter = 1charge = 1.0name = “Carl”point = (5.229,-4.78)isReadable = .true.end program
character vars: you must specify a length. This length is fixed. If you put more, it will be truncated. If you put less, the rest will be padded with spaces.
logical vars: you can use .true. or .false.
Parameter “variables”(AKA constants)
program Paramsimplicit noneinteger, parameter :: real, parameter :: AVOGADRO = 6.023d23end program
Fortran Syntax: basic math operations
program CompoundInterestimplicit noneinteger :: yearsinteger :: frequencyreal :: initialAmount, finalAmountreal :: annualRate ! as a decimal, not percentyears = 6frequency = 4initialAmount = 1500.0annualRate = 0.043finalAmount = initialAmount * (1.0 + annualRate/frequency)**(frequency*years) write (*,*) “Final Amount”, finalAmountend program
A = final amountP = initial amount r = annual nominal interest rate (as a decimal)n = number of times the interest is compounded per yeart = number of years
Note: Money math is professionally made with integers. Real math is always approximated.
+, -, *, / : basic operations** : power= : assignment to a variable
Traditional mathematical precedence order is enforced for math ops
Coercion rules
Operations within a given type generally stay in that type.Operations involving different types may coerce (force) one type into anotherAlternatively, coercion can be performed manually
program Coercionimplicit noneinteger :: numerator, denominatorreal :: numeratorReal numerator = 5 denominator = 3numeratorReal = 5.0 ! integer division write (*,*) numerator/denominator ! automatic coercion of denominator for mixed typeswrite (*,*) numeratorReal/denominator! manual coercion of denominator + automatic of numerator write (*,*) numerator/real(denominator)! totally manual coercion write (*,*) real(numerator)/real(denominator)end program
stefanos-imac:~ borini$ ./coercion 1 1.6666666 1.6666666 1.6666666
Control structures: if / else if / else / endif
program Coercionimplicit noneinteger :: age age = 5if (age < 0) then write (*,*) “still unborn”else if (age >= 0 .and. age < 18) then write (*,*) “minor”else write (*,*) “adult”endifend program
Control structures: if / else if / else / endif
program IfExampleimplicit noneinteger :: age age = 5if (age < 0) then write (*,*) ”unborn”else if (age >= 0 .and. age < 18) then write (*,*) “minor”else write (*,*) “adult”endifend program
Evaluates a logical expressionIf true, the block is executed.
Only the first satisfied condition is executed. Additional ones are not.
If all expressions are false, and and elsesection is present, it is executed.
Boolean logic operations
.and.
T
F
T
T
F
F
F
F
.or.
T
F
T
T
T
F
T
F
.not.
T
F
F
T
int/real comparison operations(evaluate to logical)
== equal
/= not equal
< lower than
> greater than
<= lower or equal than
>= greater or equal than
program DoExampleimplicit noneinteger :: loopVar do loopVar = 1, 10if (loopVar == 3) cycleif (loopVar == 5) exit write (*,*) loopVarenddoend program
Looping: do/enddo
Repeats the block a given number of timesA variable (loop variable) stores the current value.At every new repetition, the variable is incremented by oneRepetition stops when loopVar > end limit (for retrograde looping when loopVar < end limit)
The loop variable must be an integerIncrement can be different from 1 with a different syntax
do loopVar = 1, 10, 2
do loopVar = 10, 1, -1
Retrograde looping is possible
You can't change the loopVar within the loop (really bad practice in any case)
Don't rely on the last value of the loop var after the loop
program DoExampleimplicit noneinteger :: loopVar do loopVar = 1, 10if (loopVar == 3) cycleif (loopVar == 5) exit write (*,*) loopVarenddoend program
Looping: do/enddo
cyclesuspend the current loop.start immediately a new one
exit suspend the current loop.leave the loop block (resume after the enddo)
If you know another language, Fortran “do” is equivalent to a “for”
Fortran: C/C++/Pythondo : forexit : breakcycle : continue
Infinite looping
program DoExampleimplicit none dowrite (*,*) “All work and no play”enddoend program
Use exit to interrupt it
Select case
A single variable is comparedagainst a set of possible values.The block associated to the matching value is executed.Can always be replaced with an if/else if/else/endifGenerally used for convey a choiceout of possible options
program SelectExampleimplicit noneinteger :: numGuestsnumGuests = 0 select case (numGuests)case (0)write (*,*) “open canned food”case (1)write (*,*) “prepare meal”write (*,*) “light candle”case (2)write (*,*) “prepare big meal”case defaultwrite (*,*) “call pizza”end selectend program
program SelectExampleimplicit noneinteger, parameter :: ACCOUNT_TYPE_BASIC = 1integer, parameter :: ACCOUNT_TYPE_PRO = 2 integer, parameter :: ACCOUNT_TYPE_COMMERCIAL = 3integer, parameter :: ACCOUNT_TYPE_TEST = 4integer :: accountTypeaccountType = GetAccountType(id=23) select case (accountType)case (ACCOUNT_TYPE_BASIC)write (*,*) “Hi”case (ACCOUNT_TYPE_PRO)write (*,*) “Good morning”case (ACCOUNT_TYPE_COMMERCIAL)write (*,*) “Welcome to our service. We are proud to have you as our client”case (ACCOUNT_TYPE_COMMERCIAL)write (*,*) “Testing account. All features disabled”case defaultwrite (*,*) “Unrecognized account type. Call the emergency team.”end selectend program
Select caseTypical use