So, we have a few ways of entering numbers in a Fortran program. Different ways of writing the number shows it’s precision. Thus,
means a REAL
number of default KIND
. By default, at least on the GNU compiler gfortran 4.6.1, KIND=4
, which gives a 32-bit precision number, about 7 decimal places in Base 10. All of these also give the same value:
0.5_4
0.5e0
If one changes the default KIND
, for example with the gfortran compiler option -fdefault-real-8
, then the first and third of these change, but not the second, since it explicitly defines KIND=4
.
An interesting side note about binary numbers. In different bases, different numbers are rational. Take 0.1. In our normal decimal system, 0.1 is obviously rational, as it can be represented by the division of two integers, 1/10. In binary, however, this number is not rational – it is repeating. So the more precision you have in your type, the better approximation to 1/10 you have.
Here’s the big point of my post. It pays to always explicitly declare the KIND
of your constants. Example:
real*8 :: pi = 4.0_8*atan(1.0_8)
write(*,*)pi
write(*,*)0.1*pi
write(*,*)0.1_8*pi
The first line uses the built-in inverse tangent function to compute pi up to the limit of machine precision. The last two lines really highlight my point. If you run these lines in a program, you’ll see that they give two different numbers.
This is the moral of the story.
Sidenote: When declaring KIND
s of constants like this, be careful. 1_8
means the KIND=8 <em>INTEGER</em>
, not the REAL
. You need either a decimal point or scientific notation to get it to read as REAL
.