Vijay
Vijay

Reputation: 985

fortran90 reading array with real numbers

I have a list of real data in a file. The real data looks like this..

 25.935
 25.550
 24.274
 29.936
 23.122
 27.360
 28.154
 24.320
 28.613
 27.601
 29.948
 29.367

I write fortran90 code to read this data into an array as below:

PROGRAM autocorr
implicit none

INTEGER, PARAMETER :: TRUN=4000,TCOR=1800

 real,dimension(TRUN) :: angle

real :: temp, temp2, average1, average2
integer :: i, j, p, q, k, count1, t, count2

REAL, DIMENSION(0:TCOR) :: ACF

 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

open(100, file="fort.64",status="old")
do k = 1,TRUN
    read(100,*) angle(k)
end do

Then, when I print again to see the values, I get

25.934999
25.549999
24.274000
29.936001
23.122000
27.360001
28.153999
24.320000
28.613001
27.601000
29.948000
29.367001
32.122002
33.818001
21.837000
29.283001
26.489000
24.010000
27.698000
30.799999
36.157001
29.034000
34.700001
26.058001
29.114000
24.177000
25.209000
25.820999
26.620001
29.761000

May I know why the values are now 6 decimal points? How to avoid this effect so that it doesn't affect the calculation results?

Appreciate any help. Thanks

Upvotes: 0

Views: 443

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

You don't show the statement you use to write the values out again. I suspect, therefore, that you've used Fortran's list-directed output, something like this

write(output_unit,*) angle(k)

If you have done this you have surrendered the control of how many digits the program displays to the compiler. That's what the use of * in place of an explicit format means, the standard says that the compiler can use any reasonable representation of the number.

What you are seeing, therefore, is your numbers displayed with 8 sf which is about what single-precision floating-point numbers provide. If you wanted to display the numbers with only 3 digits after the decimal point you could write

write(output_unit,'(f8.3)') angle(k)

or some variation thereof.

You've declared angle to be of type real; unless you've overwritten the default with a compiler flag, this means that you are using single-precision IEEE754 floating-point numbers (on anything other than an exotic computer). Bear in mind too that most real (in the mathematical sense) numbers do not have an exact representation in floating-point and that the single-precision decimal approximation to the exact number 25.935 is likely to be 25.934999; the other numbers you print seem to be the floating-point approximations to the numbers your program reads.

If you really want to compute your results with a lower precision, then you are going to have to employ some clever programming techniques.

Upvotes: 1

Related Questions