Why are these two calculations which are exactly same giving different results in Fortran using gfortran?

166 views Asked by At
real, dimension(3), parameter :: boxlen = [4.0, 5.0, 7.0]
real, parameter :: mindist = 0.1
integer ::i

  write(*,"(A)") "Operation on array"
  print*, floor(boxlen/mindist)
  write(*,"(/A)") "Operation on individual elements"
  do i=1,3
     print*, i, floor(boxlen(i)/mindist)
  enddo

This is what I get when I run this code.

Operation on array
      40          50          70

Operation on individual elements
       1          39
       2          49
       3          69

Can someone explain why are the two calculations (one using operation on array and another using operation on individual elements) giving different results? I think they should be same.

1

There are 1 answers

19
janneb On

For me with GFortran 4.8.2 on x86_64-linux-gnu I get

Operation on array
          40          50          70

Operation on individual elements
           1          40
           2          50
           3          70

Peering into my crystall ball, if you're using 32-bit x86, there could be a difference in the order of how the computed values are stored to memory and printed.

Also, looking at the generated intermediate code with "-fdump-tree-original", it seems for the array operation, the division is done at compile time, (so should at least be correctly rounded thanks to MPFR).