# How to set double precision values in Fortran

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?

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.

• That's right, this should be the standard approach. Mar 14, 2012 at 5:46
• 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. Mar 17, 2012 at 3:20

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.

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