033. Declare floating point variables with kinds#

topic: Data types

Although floating point variables can still be declared just real or double precision in Fortran, they should not be. Instead, the kind of real should be specified as a parameter that is used throughout the program.

The code below can be changed from double to single or quadruple precision by simply changing the definition of wp (working precision) in kind_mod using the kind constants from the intrinsic iso_fortran_env module.

Note the _wp suffix used in the literal constants for \(\pi\) and \(10.0\). Any literal constant without a suffix is considered single precision in Fortran, regardless of the number of digits provided.

See https://fortran-lang.org/learn/best_practices/floating_point for more discussion.

real-precision.f90 | | 0 | Godbolt Compiler Explorer logo | Fortran logo#
module kind_mod
    use iso_fortran_env, only: real32, real64, real128  ! constants from intrinsic module
    implicit none

    integer, parameter :: wp = real64  ! or `real32`, `real128`

end module kind_mod

module area_mod
    use kind_mod, only: wp

    ! We can use a literal:
    ! real(kind=wp), parameter :: pi = 3.141592653589793238462643383279_wp
    ! Accurate up to 3.141592653589793 (15 places after decimal) with `real64`
    
    ! Or calculate:
    real(kind=wp), parameter :: pi = acos(-1.0_wp)  ! same result

contains

    pure elemental function area_circle(radius) result(area)
        real(kind=wp), intent(in) :: radius
        real(kind=wp) :: area
        area = pi*radius**2
    end function area_circle

end module area_mod

program xkind
    use kind_mod, only: wp
    use area_mod, only: area_circle
    implicit none

    real(kind=wp), parameter :: radius = 10.0_wp

    print *, area_circle(radius)

end program xkind
Output1#
   314.15926535897933     


1

Compiled using GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 with no flags