0

Can someone please explain how Fortran reads in data, particularly from text files. I thought I understood the behavior and the formatting options of I/O but the below example has me puzzled.

I am attempting to read in three values from the text file Domain.txt which contains three lines shown below

221 
500.0200 
500.0000

This file is then read by my program below

program main
implicit none
integer :: N
real    :: xmax,xmin

open(unit=1,file='Domain.txt')

read(1,*) N      ! Read first  line
read(1,*) xmax   ! Read second line
read(1,*) xmin   ! Read third  line

print*, N
print*, xmax
print*, xmin
end program

The result of this program is

      221
500.019989
500.000000

So my confusion arises with the second output for the xmax variable. Why would it read in the second line as 500.019989 and not 500.0200?

I have tried using fortran formatting format(fm.d) in the read statement to say only read in the first two digits after the decimal place, but I was never able to resolve the issue.

I am using gfortran 4.8.5. Any help would be appreciated. I also know this is somewhat a duplicate of the question asked here (Reading REAL's from file in FORTRAN 77 - odd results) but I do not have enough reputation to comment and ask a question about the solution.

Community
  • 1
  • 1
arie64
  • 572
  • 6
  • 10
  • Potentially also related is [this question](http://stackoverflow.com/q/33319357) which looks at the precision when reading from file. – francescalus Jan 19 '17 at 23:22

1 Answers1

1

The number 2/100 (which is the fractional part of 500.02) does not have a finite representation in binary. It has the infinite periodic representation 0.0000001010001111010111000010100011110101110000101... So the value will be truncated or rounded to fit into the representation model of floating point numbers and appear as such during reading. This is how all languages (including Fortran, C, C++, Java...) with a binary representation of floating point numbers react.

  • So I guess what you are saying is that Fortran can read in the string value correctly from the text file, but in converting this string to a real, it has made this conversion leading to the floating point error. I was just very confused because I wrote the output text file from a python script, and found a different results in the input of the Fortran code. – arie64 Jan 19 '17 at 21:35
  • 1
    Note the issue shows up in an obvious way because fortran's default real is only single precision. If you declare `double precision` you should see `500.0200000` printed (though the underlying issue of the binary representation not precisely matching the decimal number is still there , as it is in python as well ) – agentp Jan 19 '17 at 22:21