9
$\begingroup$

Recently, I've encountered a bizarre problem with FORTRAN95. I initialized variables X and Y as follows:

X=1.0
Y=0.1

Later I add them together and print the result:

1.10000000149012

After examining the variables, it seems as though 0.1 is not represented in double precision with full accuracy. Is there any way to avoid this?

$\endgroup$
20
$\begingroup$

Another way to do this is to first explicitly specify the precision you desire in the variable using the SELECTED_REAL_KIND intrinsic and then use this to define and initialize the variables. Something like:

INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(15)
REAL(dp) :: x
x = 1.0_dp

A nice advantage to doing it this way is that you can store the definition of dp in a module, then USE that module where needed. Now if you ever want to change the precision of your program, you only have to change the definition of dp in that one place instead of searching and replacing all the D0s at the end of your variable initializations. (This is also why I'd recommend not using the 1.0D-1 syntax to define Y as suggested. It works, but makes it harder to find and change all instances in the future.)

This page on the Fortran Wiki gives some good additional information on SELECTED_REAL_KIND.

$\endgroup$
  • $\begingroup$ That's right, this should be the standard approach. $\endgroup$ – Ondřej Čertík Mar 14 '12 at 5:46
  • $\begingroup$ And how often do people really have to change the precision on their programs blindly without going procedure by procedure anyway and testing? The main reason to use the _dp scheme is so that the precision is clearly defined in a portable way. $\endgroup$ – ja72 Mar 17 '12 at 3:20
12
$\begingroup$

You declared the variables as double precision, but you initialized them with single precision values.

You could have written:

X=1.0d0
Y=1.0d-1

Barron's answer below is another way of making a literal double precision, with the advantage that it allows you to change the precision of your variables at a later time.

$\endgroup$
  • 1
    $\begingroup$ I think that one should be using the 1.0_dp method described in the post below. $\endgroup$ – Ondřej Čertík Mar 14 '12 at 5:47
  • 1
    $\begingroup$ I second @OndřejČertík 's comment - Barron's answer is the best one. $\endgroup$ – OscarB Mar 15 '12 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.