bcumming / summer-school

9 stars 9 forks source link

fortran: kind parameters #3

Open ghost opened 10 years ago

ghost commented 10 years ago

Hi,

no big deal but the way the kind parameters are used in the fortran code are not really standard conforming. That being said, every compiler I know of does use the kind parameters such that the code works as intended, but nevertheless it's basically a compiler dependent implementation and not strictly standard conforming fortran.

real(kind=X) with any integer X is a way to tell the compiler what type of floating point (and also integer, respectively) representation to choose. BUT it is up to the compiler which integer X corresponds to which representation. There is NO guarantee that e.g. 4 denotes a 4 byte float and 8 denotes an eight byte float.

The standard conforming way to do this is to ask for a kind parameter with the desired precision, then store this and use it to define variables, etc. instead of the X above. In its most generic form, this is done through selected_real_kind and selected_int_kind. However, a simpler form is to query for the kind parameter of a given constant and then use this. http://fortranwiki.org/fortran/show/Real+precision

dmikushin commented 10 years ago

Standard-conforming Fortran often tends to be too verbose -> harder to read. In this particular case, one could use simple real type everywhere, and add compiler switch -fdefault-real-8, if it is needed to be treated as double.

bcumming commented 10 years ago

This can be done properly with low verbosity overhead, and it would prefer to have things done "properly" for a pedagogical code.

We can define the following constant in one module

integer, parameter :: dp = kind(1.d0)

Then everywhere we declare a real type use

real (kind=dp) :: alpha, residual instead of real (kind=8) :: alpha, residual

Using standards is hopefully going to be more portable across compilers, so we don't have to find equivalent PGI, Cray and Intel flags for -fdefault-real-8.