Comparing with matlab/python, fortran program runs faster for loops after compiling. Although fortran is an old language, it is capable of parallel computing and still wildly used in scientific computing today.

Hello world

First we introduce a minibird example of the fortran programming for a fresh start.

Helloworld source code

Here we demonstrate a minibird Helloworld example of the fotran programming language.

1
2
3
4
5
! helloworld.f90 test
program main
implicit none
write(*,*) "Hello !"
end

Complile and run fortran on linux

1
2
ifort/gfortran helloworld.f90 -o hello.out
./hello.out

After execute these command in terminal, you should be able to view the printed output in your terminal window. Here, ifort is for intel fortran compiler, gfortran is for GNU fortran compiler.

Function definition

Singular value function

Here we demonstrate the definition of a single value function z = f(x, y).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
program main
implicit none
real :: x = 3
real :: y = 2
real :: z
real, extent :: fun1
z = add(x, y)
write (*, *) z
end

function fun1(x, y)
implicit none
real :: x, y
real :: fun1
fun1 = x*y
return
end

Multivalue function

Here we demonstrate the definition of a multivalue function [c, d] = f(a, b). Output of more than one variable, you should use subroutine other than function. Function format in fortran can only have one output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
program main
implicit none
real :: a, b, c, d

a = 10
b = 30
call multifun(a, b, c, d)
write (*, *) a
write (*, *) b
write (*, *) c
write (*, *) d
end

subroutine multifun(a, b, c, d)
! reference [1] https://stackoverflow.com/questions
! /37120263/function-which-returns-multiple-values
implicit none
real, intent(in) :: a, b
real, intent(out):: c, d
c = a + b
d = a*b
end subroutine

Optional inputs

The optional inputs of fortran is a bit like python, where you can given the inputs of fortran variable without consider their correct order [1].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module procs
contains
real function calc (first, second, third)
implicit none
real, intent(in) :: first, second, third
calc = (first - second)/third
end function procs
end module procs

program test_keywords
use procs
implicit none
write (*,*) cals(3, 1, 2)
write (*,*) calc(first=3, second=1, third=2)
write (*,*) calc(third=2, first=3, second=1)
end program test_keywords

All the three methods to call the function cals() returns the same result regardless of the calling order of the arguments.

Reference

[1] S. Chapman, 2007, “fotran 95/2003 for scientists and engineers”, 3rd edition, McGraw-Hill press…