0

Here is my program:

program ch0501
implicit none
real :: btan
read(*,'(F20.8)'),btan
PRINT '(F20.8)', btan
end program ch0501

When run, I input 123.12345678 on the keyboard. However, I get

        123.12345886

as output on the screen.

Why is that? I tried compiling on different machines using gfortran and get the same result.

boxofchalk1
  • 493
  • 1
  • 6
  • 13
  • 4
    The closest 32 bit IEEE binary floating point number to 123.12345678 is 123.1234588623046875. – Patricia Shanahan Dec 08 '14 at 00:04
  • @PatriciaShanahan Thanks for the link! Yes, you're right - according to http://en.wikipedia.org/wiki/Single-precision_floating-point_format the REAL type is binary32 and the cause for the inconsistency. I also got the number you got after doing a lot of arithmetic by hand - out of curiosity, how did you find the closest floating point so quickly? I imagine this will be helpful in helping me to spot rounding errors quickly. – boxofchalk1 Dec 08 '14 at 03:41
  • 1
    Java has a data type, BigDecimal, that can represent exactly any terminating decimal fraction, and print it exactly. Any floating point number can be converted exactly to BigDecimal: `System.out.println(new BigDecimal(123.12345678F));`. The "F" makes the literal 32 bit, not 64 bit. – Patricia Shanahan Dec 08 '14 at 03:41
  • Thanks! I just did a Google search and found this: http://www.h-schmidt.net/FloatConverter/IEEE754.html – boxofchalk1 Dec 08 '14 at 03:48

0 Answers0