views:

33

answers:

2

I have an input file and the first line contains the following decimal.

0.5053102074297753

I have a Fortran 90 program which reads the file and outputs the value.

read(*,*) answer
write(*,"(F20.16)") answer

This is the output:

0.5053101778030396

Apparently, what is stored is not the same as what is read. The question is, Why?

+2  A: 

How is answer declared? If it is a single precision real you can only expect about 6 decimal digits of precision.

Also, values are converted to binary for internal storage and computations. This can cause rounding and other issues, but the difference here is too large for this to be the cause.

To declare answer as double precision, use the following:

integer, parameter :: DRK = selected_real_kind (14)
real (kind=DRK) :: answer

This will guarantee that answer has at least 14 decimal digits. "DRK" can be used throughout your program. Depending on your compiler, you can try asking for even more digits ... it may provide a such a type. Rarely is more than double precision necessary.

M. S. B.
That's it! I totally forgot about precision. answer was defined as real(kind=4). Thanks a lot.
blahbaa
+2  A: 

What Every Computer Scientist Should Know About Floating-Point Arithmetic.

The default real precision is not enough to store the number with 16 decimal places in the fractional part.

kemiisto