Fortran – Numerik und Hochleistungsrechnen

Fortran (Formula Translation, 1957 von IBM) ist die älteste höhere Programmiersprache und bis heute der Standard für numerische Berechnungen, Wettervorhersage und Hochleistungsrechnen (HPC). Der aktuelle Standard heißt Fortran 2023; in der Praxis dominieren Fortran 90/95 und 2008. Compiler: gfortran (GNU), Intel ifx/ifort.

Compiler & Grundlagen

  • gfortran --version – Compiler-Version prüfen
  • gfortran -O2 -o prog prog.f90 – optimiert kompilieren
  • gfortran -g -Wall -o prog prog.f90 – Debug- und Warnungs-Modus
  • gfortran -fopenmp prog.f90 – OpenMP-Parallelisierung aktivieren
  • Dateiendungen: .f (Fixed Form), .f90/.f95 (Free Form)

Basissyntax

program hello
  implicit none
  print *, 'Hallo, Welt!'
end program hello
  • implicit none – erzwingt explizite Variablendeklaration (Pflicht in modernem Code)
  • integer :: i, real :: x, double precision :: d, character(len=20) :: s, logical :: ok
  • parameter für Konstanten: real, parameter :: pi = 3.14159
  • Kommentare: ! (Free Form) bzw. c in Spalte 1 (Fixed Form)

Kontrollstrukturen

do i = 1, 10
  print *, i
end do

if (x > 0) then
  print *, 'positiv'
else if (x < 0) then
  print *, 'negativ'
else
  print *, 'null'
end if

select case (n)
case (1)
  print *, 'eins'
case default
  print *, 'anders'
end select

Arrays und Matrizen

real, dimension(100) :: a        ! 1D-Array, Index 1..100
real, dimension(10,10) :: m      ! 2D-Matrix
a(i) = 1.0
m(1,:) = 0.0                     ! erste Zeile
sum(a), maxval(a), minval(a)     ! Reduktionen
matmul(m1, m2)                   ! Matrixmultiplikation
where (a > 0) a = a * 2          ! maskierte Zuweisung

Funktionen, Subroutinen und Module

function quadrat(x) result(r)
  implicit none
  real, intent(in) :: x
  real :: r
  r = x * x
end function quadrat

subroutine tausche(a, b)
  real, intent(inout) :: a, b
  real :: tmp
  tmp = a; a = b; b = tmp
end subroutine tausche

module bündelt Funktionen, Typen und Konstanten und macht sie per use modulname importierbar – so entstehen saubere, wiederverwendbare numerische Bibliotheken.

Ein-/Ausgabe

  • print *, 'Text', variablen – Ausgabe auf die Konsole
  • read *, var – Eingabe von der Konsole
  • open(unit=10, file='daten.txt') / close(10) – Datei öffnen/schließen
  • write(10, *) werte / read(10, *) werte – in/aus Datei schreiben/lesen

Verwandte Einträge: MATLAB, Julia und R für Datenanalyse, sowie die Glossar-Begriffe Array und Algorithmus.