2

When I code in Fortran language, I find when I set REAL value as control-var in do-loop, the outputs are strange, for example:

do i=0.1,1.0,0.1
write (13,"(F15.6)") i
end do

The out puts are: 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0.But when I set the start value as 0.6:

do i=0.6,1.0,0.1
write (13,"(F15.6)") i
end do

the outputs are:0.6,0.7,0.8,0.9,and 1.0 is not outputted. Why does this happen?

Wilber
  • 41
  • 1
  • 5

1 Answers1

5

This is basically a rounding issue see Precision problems of real numbers in Fortran and the link that follows from there. Comparing two floating points is tricky and it does not play well with do loops.

You should print more decimal numbers and not just 6:

   0.1000000015
   0.2000000030
   0.3000000119
   0.4000000060
   0.5000000000
   0.6000000238
   0.7000000477
   0.8000000715
   0.9000000954
   1.0000001192

The values are not precise.

In Fortran the number of iterations is computed before starting the loop. And when you compute the loop trip count:

write (*,"(F15.10)") (1.0 - 0.1) / 0.1

write (*,"(F15.10)") (1.0 - 0.6) / 0.1

you will get:

   9.0000000000
   3.9999997616

so the latter one will be iterated only four times (3 + 1 = 4; so i = 0.6, 0.7, 0.8 and 0.9), because the count is truncated from 3.999... to 3.

Real loop counters were deleted from Fortran for good reasons, don't use them. The rounding is one of the problems. The compiler should warn you:

Warning: Deleted feature: Start expression in DO loop at (1) must be integer

Also, naming a real variable as i should be a crime.

Community
  • 1
  • 1