Subject: Re: bug#16987: Bad default mantissa width for ~g format string

From: Mark H Weaver <[email-masked]>
Date: Tue, 11 Mar 2014 11:21:36 -0400

David Kastrup <[email-masked]> writes:

> scheme@(guile-user)> (format #f "~g" (/ 1e100 3))
> $19 = "3333333333333333000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0    "
>
> That, frankly, is pretty ludicrous.  The reserved mantissa width should
> at least be constrained to the actually available precision of the data
> type.

Agreed.

> If it isn't, there is no useful way to output a variable with
> minimal width.  Using ~S instead results in the much more reasonable
> "3.333333333333333e99" but it will not convert fractions to a floating
> point representation:
>
> scheme@(guile-user)> (format #f "~g" (/ 10000000000000000000000000000000 3))
> $22 = "3333333333333333600000000000000.0    "
> scheme@(guile-user)> (format #f "~S" (/ 10000000000000000000000000000000 3))
> $23 = "10000000000000000000000000000000/3"
> scheme@(guile-user)> 

As a workaround, you can force decimal output with ~S by converting the
exact fraction to an inexact floating point number before passing it to
'format', using 'exact->inexact':

  scheme@(guile-user)> (format #f "~S" (exact->inexact (/ 10000000000000000000000000000000 3)))
  $4 = "3.3333333333333336e30"

Note that 'exact->inexact' works even if the number passed to it is
already inexact, in which case it's a no-op.

At some point we'll make ~g do the right thing for exact fractions, so
that the last digit printed is a 3, not 6.  For now, it can't be helped
because the value is being rounded twice: once in the conversion to
inexact binary, and again when converting from binary to decimal.

    Thanks,
      Mark