-1

I must have fell asleep during output formatting day in Fortran class, because these results are perplexing me. Using gfortran 4.6,

this program

program f1
  real :: x=65246514
  write(*,*) x
end program f1

results in

   65246512.0

This program

program f1
  real :: x=65245.6525
  write(*,*) x
end program f1

results in

   65245.6523 

Finally, this program

program f1
  real :: x=65226545.6525
  write(*,'(F14.4)') x
end program f1

results in

 65226544.0000

Clearly, the console output is not what is being assigned to x. Is there some finite precision result coming in to cause this?

bcf
  • 2,104
  • 1
  • 24
  • 43

1 Answers1

1

The issue is that the variable and constant are single precision and only have about 7 decimal digits available. Compare to:

program f1
  use, intrinsic :: ISO_FORTRAN_ENV
  implicit none
  real :: x=65226545.6525
  real (real64) :: y=65226545.6525_real64
  write(*,'(F14.4)') x
  write(*,'(F14.4)') y
end program f1

which uses a double-precision number via the ISO Fortran environment, specified as real64, i.e., 64 bits. real64 is also used on the constant, otherwise it will be evaluated as a single-precision constant, then stored in the double-precision variable y. (If you need even more digits, you can use quadrupole precision, real128.)

M. S. B.
  • 28,968
  • 2
  • 46
  • 73