This is the mail archive of the
fortran@gcc.gnu.org
mailing list for the GNU Fortran project.
Re: Getting equivalent 'double' parsing in c++ and fortran?
Convey, Christian J CIV NUWC NWPT wrote:
2.70000000000000017762568294... (c++)
2.70000000000000017762570000...
(fortran)
Those two decimal strings represent the same binary number.
gfortran's library uses an algorithm which will print the shortest
string of non-zero digits that will exactly represent the binary
number, that's why it stops where your C library doesn't.
Thanks, but what you're saying doesn't make much sense to me. Both
of the outputted strings are the same length.
Yes, but the non-zero part is shorter in gfortran's output, which is
what I was saying.
But that did make me wonder if there was some truncation going on.
So I increased the format strings to 'D100.90' (fortran) and
'%100.90f' (c++). The result was:
The fortran had the same output as before, except with more trailing
zeroes. So that's about 22 decimal places of not-all-zeroes output,
followed by all zeroes. In contrast, the c++ had output had 50
decimal places of not-all-zeroes output, followed by all zeroes.
Both represent the same binary number. You can simply verify this by
doing something like
double x, y;
sscanf("2.70000000000000017762568294", "%f", &x);
sscanf("2.70000000000000017762570000", "%f", &y);
printf("%80.70f\n", x - y);
which will print an exact zero. The 56 mantissa bits of a REAL*8 can be
exactly represented by ceil(56 / log10(2)) = 22 decimal digits. The
digits behind the 22nd in a decimal representation are therefore
arbitrary. gfortran chooses a more comfortable round-off than your C
library.
It's possible that this difference can be entirely attributed to
differences in the double->string formatting code employed by the two
language's runtime libraries. But how can I tell?
That's what I was trying to explain in my initial reply.
I tried comparing the 64-bit bit representations of the two programs'
variables, but I couldn't figure out how to get Fortran to print
(possibly in hex) the binrary representation of a double-precision
variable.
INTEGER*8 I
REAL*8 X
EQUIVALENCE(X,I)
... read into x
... print i
is non-standard but will work with every compiler.
Cheers,
- Tobi