Are Fortran named constants evaluated each time the containing module is used? - fortran

Say I define the parameter pi = -acos(-1.0) and save it in a module. When I use this module in another program, is the value of pi computed from the function ACOS each time?
If that's the case, is it better to define pi = -3.1415.... to whatever precision I require?

If you have a named constant defined in a module then its value must be given by a constant expression. In a compile/execute module this constant expression will typically be evaluated when compiling the module itself, rather than when it is ultimately referenced.
Either way, there is no possibility for something using a module to affect the evaluation of the named constant's value in that module.
For the example of the question, ACOS(-1.0) is evaluated using whatever the default real kind is at the time of compiling. If this is changed to something like
module pidef
use, intrinsic :: iso_fortran_env, only : piprec => real64
implicit none
real(piprec), parameter :: pi = ACOS(-1.0_piprec)
end module
then the constant expression uses the value of piprec in scope at that point. Being a constant expression every value must be well-defined by then. It will not be the case that something like
program piuse
use, intrinsic :: iso_fortran_env, only : piprec => real32
use pidef
implicit none
end program
will somehow evaluate pi using real32. Equally there is no way to reference in the module's constant expression a variable defined globally later on, after the module is compiled.

No, parameters are calculated at compile time. The performance of the two methods should be identical.
Also, if you are wondering which of two options is faster, the answer is almost always "try it and see". If you care about your code running fast, you should use a code profiler to accurately time your code and work out what is slowing it down.
N.B. while the speed should be the same, there is the issue of precision. If you define pi using acos(-1.0) it will only be accurate to default single precision. If you want to define pi like this, you should use acos(-1.0_dp), where dp defines the floating-point precision you need.

Related

What shall be used in Modern Fortran to specify a 8 bytes real variable if iso_fortran_env is not supported?

I want to specify as type of a subroutine a floating point value (real) of 8 bytes precision.
I have read here that the modern way to do it would be:
real(real64), intent(out) :: price_open(length)
However, iso_fortran_env is not supported by f2py (same as it does not support iso_c_bindings either).
I get errors of this type:
94 | real(kind=real64) price_open(length)
| 1
Error: Parameter 'real64' at (1) has not been declared or is a variable, which does not reduce to a constant expression
The link referenced before states that using kind would be the proper way if iso_fortran_env is not available and that real*8 shall be avoided.
I have been using real(8) is that equivalent to using kinds? If not, what shall I use?
What is wrong with real*8 if I want to always enforce 8 bytes floating point values?
You say you are specifically interested in interoperability with C. However, iso_c_binding, nor iso_fortran_env are supported. These modules have constants that help you to set the right kind constant for a given purpose. The one from iso_fortran_env would NOT be the right one to choose anyway, it would be c_double.
If these constants meant to help you in your choice are not available, you are on your own. Now you can choose any other method freely.
It is completely legitimate to use just kind(1.d0) and just check that the connection to C works. Automake had been doing that for ages.
Or use selected_real_kind(), it does not matter, it is really up to you. Just check that double in C ended up being the same numeric type.
The traditional thing in automatic build processes was to do many tests about which (mainly C) constant ended up having which value. You just need to check that double precision in Fortran does indeed correspond to double in C. It is very likely, but just check it. You can have a macro that changes the choice if not, but probably it is a needless work untill you actually meet such a system.

ISO_FORTRAN_ENV or -fdefault-real-8 to promote reals to double precision

I've always been using the -fdefault-real-8 option of gfortran to automatically promote every single REAL declared anywhere in the program to double precision, along with any constant, e.g. 1.23. If I ever wanted to switch back to single precision, I only had to remove that option and recompile, without changing a single character in the source code.
At a point I started using ISO_FORTRAN_ENV module, since it allows me to use constants like INPUT|OUTPUT|ERROR_UNIT, as well as IOSTAT_END and IOSTAT_EOR and others (which seemed to be a good and easy move in the direction of portability, am I wrong?). From then on, I've been seeing and ignoring the following warning
Warning: Use of the NUMERIC_STORAGE_SIZE named constant from intrinsic module ISO_FORTRAN_ENV at (1) is incompatible with option -fdefault-real-8
since such incompatibility seems to have no effect so far.
Now I'd like to get rid of this warning if it is possible and worth it.
If I correctly understood, to avoid this warning I should give up on -fdefault-real-8 option and change every REAL to REAL(real64) and/or to REAL(dp) (provided that, in the latter case, the statement USE, INTRINSIC :: ISO_FORTRAN_ENV, dp => real64 is put in that unit), which is not a difficult task for sed or vim.
Nevertheless, it seems to me that this change wouldn't be the same as using -fdefault-real-8 option, since all constants would stay single precision as long as I don't add d0 to them.
Assumed the -fdefault-real-8 option is removed and ISO_FORTRAN_ENV is used anywhere, is there any way to make any constant across the program behave as each had d0 suffix?
Whether or not this is possible, have I correctly extrapolated that I can put the following lines in a single module which is used by all others program units, each of which can then use dp as kind type parameter?
USE, INTRINSIC :: ISO_FORTRAN_ENV
INTEGER, PARAMETER :: dp = real64
I would prefer this way since I could switch to real32 or real128 or whatever by changing only that line.
If you just want to silence the warning and you do not care about the implications -fdefault-real-8 has on storage association and some Fortran standard requirements, just do not import NUMERIC_STORAGE_SIZE from the module. For example,
USE, INTRINSIC :: ISO_FORTRAN_ENV, only: INPUT_UNIT,OUTPUT_UNIT,ERROR_UNIT
Assumed the -fdefault-real-8 option is removed and ISO_FORTRAN_ENV is used anywhere, is there any way to make any constant across the program behave as each had d0 suffix?
No.
By the way, d0 is exactly the same as double precision, so that doesn't fixate much either, since the meaning of double precision is allowed to vary as much as real.
Whether or not this is possible, have I correctly extrapolated that I can put the following lines in a single module which is used by all others program units, each of which can then use dp as kind type parameter?
Yes. That is a common practice.

Is it possible to make user-defined KIND parameters globally available?

Consider the following code:
module numbers
integer, parameter :: sing_prec = selected_real_kind(6)
integer, parameter :: doub_prec = selected_real_kind(15)
end module
Whenever I want to use variables of type real(sing_prec) :: foo or similar somewhere within my code, I need to insert use numbers in the respective program unit. Is it possible to do that in a "global" fashion, i.e. make the KIND definitions globally available?
Are there any implications to this? If the types are required in many places, inserting use statements everywhere makes the code quited bloated. Something similiar to compiler flags such as -fimplicit none in gfortran for imposing implicit noneeverywhere would be great, but I was not able to find such a flag.
This question is not restricted to a specific Fortran version.
In standard Fortran - No.
In compiler specific implementations of Fortran - Not as far as I am aware with the current crop of widely used compilers. All (?) have options to treat default reals (integers, complexes, too) as either 4- or 8-byte, but not to selectively treat some as 4- and some as 8- (or whatever lengths you wish to make use of).
You could hack it I guess -- maybe put all code in one scope ?
Arrrgggh you recoil in horror, all the code in one scope !!!
which kind of takes me to this point => Most recent programming languages and systems have tended towards increasing modularisation and think it a good thing to explicitly import definitions from one scope to another. Fortran uses use but other similar mechanisms in other languages go under the labels of import, include, and similar.
By the way, you do know about the intrinsic module iso_fortran_env don't you ? You might rewrite your snippet along the lines
use iso_fortran_env, sing_prec => real32, doub_prec => real64

CABS(x) function for complex(8)

Is there an absolute value function for a complex value in double precision? When I try CABS() I get
V(1,j) = R(j,j) + (R(j,j)/cabs(R(j,j)))*complexnorm2(R(j:m,j))
"Error: Type of argument 'a' in call to 'cabs' at (1) should be
COMPLEX(4), not COMPLEX(8)"
I have read there's a function called CDABS() but I wasnt sure if that was the same thing?
There is no reason using anything else than ABS(). Generics for intrinsic procedures were already present in FORTRAN 77. You can use them for all intrinsic numeric types.
If you want to see the table of available specific functions of the generic ABS(), see https://gcc.gnu.org/onlinedocs/gfortran/ABS.html , but they are mostly useful only to be passed as actual arguments. You can see that CDABS() is a non-standard extension and I do not recommend to use it.
CABS is defined by the standard to take an argument of type default complex. In your implementation this looks like complex(kind=4). There is no standard function CDABS, although your implementation may perhaps offer one: read the appropriate documentation.
Further, there is no standard specific function for the generic function ABS which takes a double complex argument. Again, your implementation may offer one called something other than CDABS.
That said, the generic function ABS takes any integer, real, or complex argument. Use that.
COMPLEX*8 and complex(KIND=8) are not the same.
The first one, is 4 byte real and 4 byte imaginary.
The complex(KIND=8) or COMPLEX(KIND=C_DOUBLE) is actually a double precision real and double precision imaginary... So equivalent to COMPLEX*16.
As mentioned ABS() should be fine.

Fortran 90 kind parameter

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?
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.
I suggest using the Fortran 2008 and later; INT8, INT16, INT32, INT64, REAL32, REAL64, REAL128. This is done by calling ISO_FORTRAN_ENV in Fortran 2003 and later. Kind parameters provides inconsistent way to ensure you always get the appropriate number of bit representation
Just expanding the other (very good) answers, specially Andrej Panjkov's answer:
The KIND of a variable is an integer label which tells the compiler
which of its supported kinds it should use.
Exactly. Even though, for all the numeric intrinsic types, the KIND parameter is used to specify the "model for the representation and behavior of numbers on a processor" (words from the Section 16.5 of the standard), that in practice means their bit model, that's not the only thing a KIND parameter may represent.
A KIND parameter for a type is any variation in its nature, model or behavior that is avaliable for the programmer to choose at compile time. For example, for the intrinsic character type, the kind parameter represents the character sets avaliable on the processor (ASCII, UCS-4,...).
You can even define your own model/behaviour variations on you defined Derived Types (from Fortran 2003 afterwards). You can create a Transform Matrix type and have a version with KIND=2 for 2D space (in which the underlying array would be 3x3) and KIND=3 for 3D space (with a 4x4 underlying array). Just remember that there is no automatic kind conversion for non-intrinsic types.
From the Portland Group Fortran Reference, the KIND parameter "specifies a precision for intrinsic data types." Thus, in the declaration
real(kind=4) :: float32
real(kind=8) :: float64
the variable float64 declared as an 8-byte real (the old Fortran DOUBLE PRECISION) and the variable float32 is declared as a 4-byte real (the old Fortran REAL).
This is nice because it allows you to fix the precision for your variables independent of the compiler and machine you are running on. If you are running a computation that requires more precision that the traditional IEEE-single-precision real (which, if you're taking a numerical analysis class, is very probable), but declare your variable as real :: myVar, you'll be fine if the compiler is set to default all real values to double-precision, but changing the compiler options or moving your code to a different machine with different default sizes for real and integer variables will lead to some possibly nasty surprises (e.g. your iterative matrix solver blows up).
Fortran also includes some functions that will help pick a KIND parameter to be what you need - SELECTED_INT_KIND and SELECTED_REAL_KIND - but if you are just learning I wouldn't worry about those at this point.
Since you mentioned that you're learning Fortran as part of a class, you should also see this question on Fortran resources and maybe look at the reference manuals from the compiler suite that you are using (e.g. Portland Group or Intel) - these are usually freely available.
One of the uses of kind could be to make sure that for different machine or OS, they truly use the same precision and the result should be the same. So the code is portable. E.g.,
integer, parameter :: r8 = selected_real_kind(15,9)
real(kind=r8) :: a
Now this variable a is always r8 type, which is a true "double precision" (so it occupies 64 bits of memory on the electronic computer), no matter what machine/OS the code is running on.
Also, therefore you can write things like,
a = 1.0_r8
and this _r8 make sure that 1.0 is converted to r8 type.
To summarize other answers: the kind parameter specifies storage size (and thus indirectly, the precision) for intrinsic data types, such as integer and real.
However, the recommended way now is NOT to specify the kind value of variables in source code, instead, use compiler options to specify the precision we want. For example, we write in the code: real :: abc and then compile the code by using the compiling option -fdefault-real-8 (for gfortran) to specify a 8 byte float number. For ifort, the corresponding option is -r8.
Update:
It seems Fortran experts here strongly object to the recommended way stated above. In spite of this, I still think the above way is a good practice that helps reduce the chance of introducing bugs in Fortran codes because it guarantees that you are using the same kind-value throughout your program (the chance that you do need use different kind-values in different parts of a code is rare) and thus avoids the frequently encountered bugs of kind-value mismatch between dummy and actual arguments in a function call.