Fortran 90 kind parameter

Lana picture Lana · May 8, 2009 · Viewed 57.9k times · Source

I am having trouble understanding Fortran 90's kind parameter. As far as I can tell, it does not determine the precision (i.e., float or double) of a variable, nor does it determine the type of a variable.

So, what does it determine and what exactly is it for?

Answer

Andrej Panjkov picture Andrej Panjkov · May 13, 2009

The KIND of a variable is an integer label which tells the compiler which of its supported kinds it should use.

Beware that although it is common for the KIND parameter to be the same as the number of bytes stored in a variable of that KIND, it is not required by the Fortran standard.

That is, on a lot of systems,

REAl(KIND=4) :: xs   ! 4 byte ieee float
REAl(KIND=8) :: xd   ! 8 byte ieee float
REAl(KIND=16) :: xq   ! 16 byte ieee float

but there may be compilers for example with:

REAL(KIND=1) :: XS   ! 4 BYTE FLOAT
REAL(KIND=2) :: XD   ! 8 BYTE FLOAT
REAL(KIND=3) :: XQ   ! 16 BYTE FLOAT

Similarly for integer and logical types.

(If I went digging, I could probably find examples. Search the usenet group comp.lang.fortran for kind to find examples. The most informed discussion of Fortran occurs there, with some highly experienced people contributing.)

So, if you can't count on a particular kind value giving you the same data representation on different platforms, what do you do? That's what the intrinsic functions SELECTED_REAL_KIND and SELECTED_INT_KIND are for. Basically, you tell the function what sort of numbers you need to be able to represent, and it will return the kind you need to use.

I usually use these kinds, as they usually give me 4 byte and 8 byte reals:

!--! specific precisions, usually same as real and double precision
integer, parameter :: r6 = selected_real_kind(6) 
integer, parameter :: r15 = selected_real_kind(15) 

So I might subsequently declare a variable as:

real(kind=r15) :: xd

Note that this may cause problems where you use mixed language programs, and you need to absolutely specify the number of bytes that variables occupy. If you need to make sure, there are enquiry intrinsics that will tell you about each kind, from which you can deduce the memory footprint of a variable, its precision, exponent range and so on. Or, you can revert to the non-standard but commonplace real*4, real*8 etc declaration style.

When you start with a new compiler, it's worth looking at the compiler specific kind values so you know what you're dealing with. Search the net for kindfinder.f90 for a handy program that will tell you about the kinds available for a compiler.