-4

The code is below:

program error
implicit none
real :: l,h
integer :: r
l=1.0
h=0.2
r=l/h
print*,r
end program error

The problem is that the answer is 4. When I explicitly divide 1.0 by 0.2, the answer is 5, but when I use symbols, it is 4. In addition, for instance, 1.0/h and l/0.2 is also 4. I am really confused. When I define r as real number, the problem is gone; but I need it to be an integer since I am going to use those variables to define a two dimensional array.

Foltran
  • 5
  • 4

2 Answers2

1

You are hitting a problem with rounding of real numbers.

0.2 is not a number that can be represented exactly in binary, so 1/0.2 is also not exactly 5, but can be slightly different. So, it is possible that it is evaluated to 4.999997 (or something like that).

Second, assignment of a real to an integer truncates, so in your case, it probably happened to be 4 instead of 5. If you want to assign to the nearest integer, use r = nint(l/h) instead.

Also, read What Every Computer Scientist Should Know About Floating Point Arithmetic.

This has nothing to do with Fortran specifically, it is a general property of floating point arithmetic. The same thing could happen, for example, in C.

Community
  • 1
  • 1
1

Use the NINT (nearest integer) function to get the nearest integer. The problem with your code is that setting an integer variable to a real number even slightly less than 5 will set it to 4, as demonstrated by the program below. The expression 1.0/0.2 may be computed as slightly less than 5 due to the finite precision of floating point arithmetic.

program error
implicit none
real :: l,h
integer :: r
l=1.0
h=0.2
r=nint(l/h)
print*,r ! gives 5
r = 4.99999
print*,r ! gives 4
end program error
Fortranner
  • 2,525
  • 2
  • 22
  • 25