fortran refcard
DESCRIPTION
Fortran RefcardTRANSCRIPT
-
Modern Fortran Reference Card(c) 2014 Michael Goerz http://www.michaelgoerz.netThis work is licensed under the Creative CommonsAttribution-Noncommercial-Share Alike 3.0 License. To view a copyof this license, visit http://creativecommons.org/licenses/by-nc-sa/
1 Data Types1.1 Simple Data Typesinteger(specs)[,attrs] :: i integerreal(specs)[,attrs] :: r real numbercomplex(specs)[,attrs] :: z complex numberlogical(specs)[,attrs] :: b boolean variablecharacter(specs)[,attrs] :: s stringreal, parameter :: c = 2.9e1 constant declarationreal(idp) :: d; d = 1.0d0 double precision reals2=s(2:5); s2=s(:5); s2=s(5:) substring extractionattributes: parameter, pointer, target, allocatable,dimension, public, private, intent, optional, save,external, intrinsicspecs: kind=..., for character: len=...double precision: integer, parameter :: idp = kind(1.0d0)1.2 Derived Data Typestype person t define derived data typecharacter(len=10) :: nameinteger :: age
end type person ttype group ttype(person t),allocatable & F2008 : allocatable . . .& :: members(:) . . . components
end type group tname = group%members(1)%name access structure component1.3 Arrays and Matricesreal :: v(5) explicit array, index 1..5real :: a(-1:1,3) 2D array, index -1..1, 1..3real, allocatable :: a(:) deferred shape arraya=(/1.2,b(2:6,:),3.5/) array constructorv = 1/v + a(1:5,5) array expressionallocate(a(5),b(2:4),stat=e) array allocationdealloate(a,b) array de-allocation1.4 Pointers (avoid!)real, pointer :: p declare pointerreal, pointer :: a(:) deferred shape arrayreal, target :: r define targetp => r set pointer p to rassociated(p, [target]) pointer assoc. with target?nullify(p) associate pointer with NUL1.5 Operators.lt. .le. .eq. .ne. .gt. .ge. relational operators< >= relational op aliases.not. .and. .or. .eqv. .neqv. logical operatorsx**(-y) exponentiationAB//CD string concatenation
2 Control Constructsif (...) action if statementif (...) then if-constructblock
else if (...) then; blockelse; blockend ifselect case (number) select-constructcase (:0) everything up to 0 (incl.)block
case (1:2); block number is 1 or 2case (3); block number is 3case (4:); block everything up from 4 (incl.)case default; block fall-through case
end selectouter: do controlled do-loopinner: do i=from,to,step counter do-loopif (...) cycle inner next iterationif (...) exit outer exit from named loop
end do innerend do outerdo while (...);block;end do do-while loop
3 Program Structureprogram myprog main programuse foo, lname => usename used module, with renameuse foo2, only: [only-list] selective useimplicit none require variable declarationinterface;...;end interface explicit interfacesspecification-statements var/type declarations etc.exec-statements statementsstop message terminate program
containsinternal-subprograms subroutines, functions
end program myprogmodule foo module
use bar used modulepublic :: f1, f2, ... list public subroutinesprivate make private by defaultinterface;...;end interface explicit interfacesspecification statements var/type declarations, etc.
containsinternal-subprograms module subprograms
end module foofunction f(a,g) result r function definitionreal, intent(in) :: a input parameterreal :: r return typeinterface explicit interface blockreal function g(x) dummy var g is functionreal, intent(in) :: x
end function gend interfacer = g(a) function call
end function frecursive function f(x) ... allow recursionelemental function f(x) ... work on args of any rank
subroutine s(n,i,j,a,b,c,d,r,e) subroutine definitioninteger, intent(in) :: n read-only dummy variableinteger, intent(inout) :: i read-write dummy variableinteger, intent(out) :: j write-only dummy variablereal(idp) :: a(n) explicit shape dummy arrayreal(idp) :: b(2:,:) assumed shape dummy arrayreal(idp) :: c(10,*) assumed size dummy arrayreal, allocatable :: d(:) deferred shape (F2008 )character(len=*) :: r assumed length stringinteger, optional :: e optional dummy variableinteger :: m = 1 same as integer,save::m=1if (present(e)) ... presence checkreturn forced exit
end subroutine scall s(1,i,j,a,b,c,d,e=1,r="s") subroutine callNotes: explicit shape allows for reshaping trick (no copies!):
you can pass array of any dim/shape, but matching size. assumed shape ignores lbounds/ubounds of actual argument deferred shape keeps lbounds/ubounds of actual argument subroutines/functions may be declared as pure (no side effects)Use of interfaces: explicit interface for external or dummy proceduresinterface
interface body sub/function specsend interface generic/operator/conversion interfaceinterface generic-spec
module procedure list internal subs/functionsend interfacegeneric-spec can be any of the following:1. generic name, for overloading routines2. operator name (+ -, etc) for defining ops on derived types
You can also define new operators names, e.g. .cross.Procedures must be one- or two-argument functions.
3. assignment (=) for defining assignments for derived types.Procedures must be two-argument subroutines.
The generic-spec interfaces should be used inside of a module;otherwise, use full sub/function specs instead of moduleprocedure list.
4 Intrinsic Procedures4.1 Transfer and Conversion Functionsabs(a) absolute valueaimag(z) imag. part of complex zaint(x, kind), anint(x, kind) to whole number realdble(a) to double precisioncmplx(x, y, kind) create x + i ycmplx(x, kind=idp) real to dp complexint(a, kind), nint(a, kind) to int (truncated/rounded)real(x, kind) to real (i.e. real part)char(i, kind), achar(i) char of ASCII codeichar(c), iachar(c) ASCII code of characterlogical(l, kind) change kind of logical libits(i, pos, len) extract sequence of bitstransfer(source, mold, size) reinterpret data
-
4.2 Arrays and Matricesallocated(a) check if array is allocatedlbound(a,dim) lowest index in arrayubound(a,dim) highest index in arrayshape(a) shape (dimensions) of arraysize(array,dim) extent of array along dimall(mask,dim) all .true. in logical array?any(mask,dim) any .true. in logical array?count(mask,dim) number of true elementsmaxval(a,d,m) max value in masked arrayminval(a,d,m) min value in masked arrayproduct(a,dim,mask) product along masked dimsum(array,dim,mask) sum along masked dimmerge(tsrc,fsrc,mask) combine arrays as mask sayspack(array,mask,vector) packs masked array into vect.unpack(vect,mask,field) unpack vect into masked fieldspread(source,dim,n) extend source array into dim.reshape(src,shp,pad,ord) make array of shape from srccshift(a,s,d) circular shifteoshift(a,s,b,d) end-off shifttranspose(matrix) transpose a matrixmaxloc(a,mask) find pos of max in arrayminloc(a,mask) find pos of min in array4.3 Computation Functionsceiling(a), floor(a) to next higher/lower intconjg(z) complex conjugatedim(x,y) max(x-y, 0)max(a1,a2,..), min(a1,..) maximum/minimumdprod(a,b) dp product of sp a, bmod(a,p) a mod pmodulo(a,p) modulo with sign of a/psign(a,b) make sign of a = sign of bmatmul(m1,m2) matrix multiplicationdot product(a,b) dot product of vectorsmore: sin, cos, tan, acos, asin, atan, atan2,sinh, cosh, tanh, exp, log, log10, sqrt4.4 Numeric Inquiry and Manipulation Functionskind(x) kind-parameter of variable xdigits(x) significant digits in modelbit size(i) no. of bits for int in modelepsilon(x) small pos. number in modelhuge(x) largest number in modelminexponent(x) smallest exponent in modelmaxexponent(x) largest exponent in modelprecision(x) decimal precision for reals inradix(x) base of the modelrange(x) dec. exponent range in modeltiny(x) smallest positive numberexponent(x) exponent part of x in modelfraction(x) fractional part of x in modelnearest(x) nearest machine numberrrspacing(x) reciprocal of relative spacingscale(x,i) x b**iset exponent(x,i) x b**(i-e)spacing(x) absolute spacing of model
4.5 String Functionslge(s1,s2), lgt, lle, llt string comparisonadjustl(s), adjustr(s) left- or right-justify stringindex(s,sub,from back) find substr. in string (or 0)trim(s) s without trailing blankslen trim(s) length of trim(s)scan(s,setd,from back) search for any char in setverify(s,set,from back) check for presence of set-charslen(string) length of stringrepeat(string,n) concat n copies of string4.6 Bit Functionsbtest(i,pos) test bit of integer valueiand(i,j),ieor(i,j),ior(i,j) and, xor, or of bit in 2 integersibclr(i,pos),ibset(i,pos) set bit of integer to 0 / 1ishft(i,sh),ishftc(i,sh,s) shift bits in inot(i) bit-reverse integer4.7 Misc Intrinsic Subroutinesdate and time(d,t,z,v) put current time in d,t,z,vmvbits(f,fpos,len,t,tpos) copy bits between int varsrandom number(harvest) fill harvest randomlyrandom seed(size,put,get) restart/query random generatorsystem clock(c,cr,cm) get processor clock info
5 Input/Output5.1 Format Statementsfmt = "(F10.3,A,ES14.7)" format stringIw Iw.m integer formBw.m Ow.m Zw.m binary, octal, hex integer formFw.d decimal form real formatEw.d exponential form (0.12E-11)Ew.dEe specified exponent lengthESw.d ESw.dEe scientific form (1.2E-10)ENw.d ENw.dEe engineer. form (123.4E-12)Gw.d generalized formGw.dEe generalized exponent formLw logical format (T, F)A Aw characters formatnX horizontal positioning (skip)Tc TLc TRc move (absolute, left, right)r/ vert. positioning (skip lines)r(...) grouping / repetition: format scanning controlS SP SS sign controlBN BZ blank control (blanks as zeros)w full length, m minimum digits, d dec. places, e exponentlength, n positions to skip, c positions to move, r repetitions5.2 Argument Processing / OS Interactionn = command_argument_count()call get_command_argument(2, value) ! get 2nd argcall get_environment_variable(name, && value, length, status, trim_name) ! optionalcall execute_command_line(command, && wait, exitstat, cmdstat, cmdmsg) ! optionalThese are part of F2003/F2008. Older Fortran compilers mighthave vendor extensions: iargc, getarg, getenv, system
5.3 Reading and Writing to Filesprint (I10), 2 print to stdout with formatprint *, "Hello World" list-directed I/O (stdout)write(*,*) "Hello World" list-directed I/O (stdout)write(unit, fmt, spec) list write list to unitread(unit, fmt, spec) list read list from unitopen(unit, specifiers) open fileclose(unit, specifiers) close fileinquire(unit, spec) inquiry by unitinquire(file=filename, spec) inquiry by filenameinquire(iolength=iol) outlist inquiry by output item listbackspace(unit, spec) go back one recordendfile(unit, spec) write eof recordrewind(unit, spec) jump to beginning of file5.4 I/O Specifiers (open statement)iostat=error save int error code to errorerr=label label to jump to on errorfile=filename name of file to openstatus=old new replace status of input file
scratch unknownaccess=sequential direct access methodform=formatted unformatted formatted/unformatted I/Orecl=integer length of recordblank=null zero ignore blanks/treat as 0position=asis rewind position, if sequential I/O
appendaction=read write read/write mode
readwritedelim=quote apostrophe delimiter for char constants
nonepad=yes no pad with blanksclose-specifiers: iostat, err, status=keep deleteinquire-specifiers: access, action, blank, delim, direct,exist, form, formatted, iostat, name, named, nextrec,number, opened, pad, position, read, readwrite, recl,sequential, unformatted, write, iolengthbackspace-, endfile-, rewind-specifiers: iostat, err5.5 Data Transfer Specifiersiostat=error save int error code to erroradvance=yes no new line?err=label label to jump to on errorend=label label to jump to on EOFeor=label label for end of recordrec=integer record number to read/writesize=integer-variable number of characters read
For a complete reference, see: Adams, Brainerd, Martin, Smith, Wagener,
Fortran 90 Handbook, Intertext Publications, 1992.There are also editions for Fortran 95, and Fortran 2003.For Fortran 2008 features, please consult: Reid, The new features of Fortran 2008.
ACM Fortran Forum 27, 8 (2008). Szymanski. Mistakes in Fortran that might surprise you:
http://t.co/SPa0Y5uB
Data TypesSimple Data TypesDerived Data TypesArrays and MatricesPointersOperators
Control ConstructsProgram StructureIntrinsic ProceduresTransfer and Conversion FunctionsArrays and MatricesComputation FunctionsNumeric Inquiry and Manipulation FunctionsString FunctionsBit FunctionsMisc Intrinsic Subroutines
Input/OutputFormat StatementsArgument Processing / OS InteractionReading and Writing to FilesI/O SpecifiersData Transfer Specifiers