Fortran

Guide To Learn

Exercise 2: Defining the set_gaussian subroutine in a module

The task is to define the set_gaussian subroutine, which sets the values of an input array to a specific shape, in its own module. The solution is analogous to defining the diff function in the mod_diff module. This time, we’re defining the set_gaussian procedure in the mod_initial module, as shown in the following listing.

Listing 4.12 Defining the set_gaussian subroutine in a custom module

module mod_initial
  use iso_fortran_env, only: int32, real32           ❶
  implicit none                                      ❷
contains
 
  pure subroutine set_gaussian(x, icenter, decay)    ❸
    real(real32), intent(in out) :: x(:)
    integer(int32), intent(in) :: icenter
    real(real32), intent(in) :: decay
    integer(int32) :: i
    do concurrent(i = 1:size(x))
      x(i) = exp(-decay * (i - icenter)**2)
    end do
  end subroutine set_gaussian
 
end module mod_initial

❶ Imports standard type kinds

❷ Enforces explicit declaration in the whole module

❸ Defines the subroutine after the contains statement

Like with the diff function and the mod_diff module, we’ll import this subroutine in the main program, as shown in the following listing.

Listing 4.13 Importing the set_gaussian subroutine from the mod_initial module

program tsunami
 
  use mod_diff, only: diff                 ❶
  use mod_initial, only: set_gaussian      ❷
  implicit none
  ...

❶ Imports the diff function from the mod_diff module

❷ Imports the set_gaussian subroutine from the mod_initial module

All external procedures that we use in the main program are now defined in their own modules. This will become especially useful as our tsunami simulator grows and becomes more complex.

Exercise 2: Defining the set_gaussian subroutine in a module

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top