Reputation: 5836
I assigned a real variable in Fortran code as a=0.00001
. On printing the variable on following line gave a=9.9999997473787516E-006
instead of 1E-5
.
The fix for this problem is declaring a=0.00001_8
or a=0.00001_rk
with rk
defined with value 8
.
I want to avoid this underscore
style in my programming. Is there a way to do this without underscores as is in C
or C++
Upvotes: 0
Views: 1094
Reputation: 2179
I'll list a couple options here, but ultimately the answer is use the underscore notation. Especially when developing new code, all real variables should use a kind
parameter. There are several good many ways to define a kind parameter:
ISO_FORTRAN_ENV
has reals and integers defined by their size: REAL32
, REAL64
, INT32
, INT64
, and others.SELECTED_REAL_KIND
to obtain a kind with the specified precision and exponent rangeIEEE_SELECTED_REAL_KIND
for IEEE compatabilityISO_C_BINDING
contains C_DOUBLE
and others for C interoperabilityThis way, you can achieve the desired precision on any machine. For example,
use ISO_FORTRAN_ENV, only : wp => REAL64
real(wp) :: x
The important part is to have wp
be explicitly declared. Then, if you want x to have the value 0.1, you set it equal to 0.1 represented using the wp
kind using
x = 0.1_wp
This is the fortran notation. You should not reject it simply because you think it's less readable.
However, I will include a couple other options. They're not as good though!
Declare constants using d
instead of e
, which requests double precision
, for example x = 0.1d0
Use a compiler flag to change the default real kind. In gfortran
, you would typically use -fdefault-real-8 -fdefault-double-8
. This compiler option doesn't always exist (certainly not in the exact same way), and also limits the possible real kinds you can declare.
Upvotes: 2
Reputation: 1274
You may use the exponent D instead of E :
a=0.00001d0
which is only useful if your variable a has been declared either double precision of real(rk) wih rk defined as :
integer,parameter :: rk=selected_real_kind(15,100)
In addition, don't use _8
but _rk
(_8
is not portable).
Upvotes: 0