benni
benni

Reputation: 43

Fortran 95: Conversion from 8 digit integer to real ends in even real number

I am trying for hours to convert an integer, lets say 33333333 to a real using the intrinsic function real(int). What I am ending up with are only the nearest even number, sometimes 33333332 or 33333334. Using integers with less than 8 digits everything works fine. Some numbers with 1 at the beginning of the 8 digits work as well, but from 20000001 on I get a wrong real...

Any suggestions?

My system: ubuntu 14.04 LTS and gcc 4.8.4

Upvotes: 1

Views: 4649

Answers (1)

Jauch
Jauch

Reputation: 1518

This simple program shows the difference of using a single versus a double during the conversion:

program compare
    implicit none

    real*8 :: real_8_v
    real*4 :: real_4_v
    integer :: integer_v

    integer_v = 33333333
    real_4_v = real(integer_v, 4)
    real_8_v = real(integer_v, 8)

    write(*, '(E15.8)') real_4_v
    write(*, '(E15.8)') real_8_v
end program compare

The result will be:

0.33333332E+08 <= single precision

0.33333333E+08 <= double precision

In IEEE754, that governs this, the "precision" of single precision numbers (32 bits) goes up to 7 digits only. When dealing with double precision numbers (64bits) it goes up to 15 digits.

Upvotes: 0

Related Questions