0

I am new to Fortran90 , I have write a simple program to add two floating point numbers as follows:

program Numbers_sum

  implicit none

  REAL :: sum
  sum = 1.6+2
  print*,"Sum =", sum
  end

I am getting the answer as Sum = 3.5999999

Why it is not getting 3.6. How Can I make this program to get the exact answer?? Any help will be appreciated.

Santhucool
  • 1,656
  • 2
  • 36
  • 92
  • @francescalus nope it is not. Just read carefully. It is Fortran. I tried C++ and Python also no such issue!! – Santhucool Apr 23 '15 at 12:34
  • 1
    This is a question about floating point numbers. There is a difference, perhaps, between what happens in C and Python, but you are using what is likely to be a single precision IEEE number rather than double. Fundamentally, you'll need to understand that other question/answers before Fortran becomes important: even `1.6d0+2d0` will not give you `3.6`. – francescalus Apr 23 '15 at 12:41
  • @francescalus ok I agree. But then why C++ and Python gives the correct answer as 3.6 insted of 3.5999999.????????? – Santhucool Apr 23 '15 at 12:45
  • In double precision 1.6+2 is much closer to 3.6 than the same in single precision. It could just be a formatting thing (I'm not sufficiently familiar with those languages) rather than an exact representation. – francescalus Apr 23 '15 at 12:50
  • @francescalus ok buddy. Is there any way in Fortran to approximate my sum? I mean to make it 3.6? Please guide me – Santhucool Apr 23 '15 at 12:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76053/discussion-between-santhucool-and-francescalus). – Santhucool Apr 23 '15 at 12:51

1 Answers1

0

There is no way to write 3.6 in base 2 with finite digits. It's 2 + 1 + 1/2 + 1/16 + ...

You can, however, hide the rounding error by selecting proper formatting:

write(*, '(F11.6)') sum

If you want to calculate in higher precision, you could use this:

REAL(KIND=8) :: var

Or, if you want to be really proper:

program numbers_sum
  implicit none
  integer, parameter :: dp = selected_real_kind(P=12)
  real(kind=dp) :: sum1
  sum1 = 1.6_dp + 2
  print *, "Sum = ", sum1
end

But even this won't eliminate the rounding completely.

Cheers

chw21
  • 7,970
  • 1
  • 16
  • 31
  • I am getting errors : sum.for: In program `numbers_sum': sum.for:3: integer, parameter :: dp = selected_real_kind(P=12) ^ Fortran 90 feature at (^) unsupported sum.for:3: integer, parameter :: dp = selected_real_kind(P=12) ^ Invalid declaration of or reference to symbol `selected_real_kind' at (^) [initi ally seen at (^)] sum.for:3: integer, parameter :: dp = selected_real_kind(P=12) ^ ... – Santhucool Apr 23 '15 at 14:00