↜ Back to index Introduction to Numerical Analysis 2

Fun with numbers

Fortran variables

Fortran implicitly assumes variables with names i, j, …, n are integers (整数) and everything else is a real number (実数) (with single precision 単精度).

Because of that, code like

i = 2.5
if (i == 2.5) then
    print *, "Equal"
else
    print *, "Math is wrong!"
endif

end

outputs Math is wrong! because i is an integer, so the value that gets stored in the assignment i = 2.5 happens to be 2.

i = 2.5
print *, i
end

outputs 2.

This can lead to tricky bugs. For example, suppose that you are working with a variable i but make a typo:

i = 5
print *, j * 4
end

Did you spot it? What does this program print?

Therefore most of modern Fortran code includes the statement implicit none at the beginning of the program, which will require you to declare every variable that you will be using:

implicit none
integer :: i

i = 5
print *, j * 4      ! this is now a compile-time error
end

Disaster averted!

Real numbers

Fortran, as well as C/C++ and other computers in general, has two types of real numbers: single precision (単精度実数) and double precision (倍精度実数).

real  x                         ! single precision
real(8) y, z                    ! double precision

x = 8000.0 / 9.0
y = 8000.0 / 9.0
z = 8000.0d0 / 9.0d0

print "(f25.20)", x
print "(f25.20)", y
print "(f25.20)", z

print "(f25.20)", x * 9.0 - 8000.0
print "(f25.20)", y * 9.0 - 8000.0

print *, "This is what Fortran thinks 0.9 is:"
print "(f25.20)", 0.9
print "(f25.20)", 0.9d0

end

This prints:

 888.88891601562500000000
 888.88891601562500000000
 888.88888888888891415263
   0.00000000000000000000
   0.00024414062500000000
 This is what Fortran thinks 0.9 is:
   0.89999997615814208984
   0.90000000000000002220

Variable x is a single precision variable and therefore only the first 6 or 7 digits are expected to be correct. y and z are double precision so around 13 to 15 are expected to be correct. However, usual constants like 9.0 are single precision and therefore the calculation to find y is performed in single precision. To really use double precision calculation, we need to use constants with suffix d0 like 9.0d0.

The last two lines might be the most surprising. They illustrate how tricky real numbers are on a computer. Both x and y appear to have the same value, the result of the same operation is very different.