Precision problems of real numbers in Fortran

saladoil picture saladoil · Apr 4, 2012 · Viewed 9k times · Source

I've been trying to use Fortran for my research project, with the GNU Fortran compiler (gfortran), latest version, but I've been encountering some problems in the way it processes real numbers. If you have for example the code:

program test
implicit none

real :: y = 23.234, z

z = y * 100000
write(*,*) y, z

end program

You'll get as output:

23.23999    2323400.0 

I find this really strange. Can someone tell me what's exactly happening here? Looking at z I can see that y does retain its precision, so for calculations that shouldn't be a problem I suppose. But why is the output of y not exactly the same as the value that I've specified, and what can I do to make it exactly the same?

Answer

milancurcic picture milancurcic · Apr 4, 2012

This is not a problem - all you see is floating-point representation of the number in the computer. The computer cannot handle real numbers exactly, but only approximations of them. A good read about this can be found here: What Every Computer Scientist Should Know About Floating-Point Arithmetic.