lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Sep 8, 2013 at 8:58 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2013/9/8 Coda Highland <chighland@gmail.com>:
>
>> So there IS a valid question to be asked here: Why SHOULDN'T
>> tostring() use %.16g?
>
> What are you using tostring() for?
>
> (1) To give something that satisfies tonumber(tostring(x)) == x.
> (2) To print out only correct digits of the number that x is supposed
>   to represent.
>
> Now, log(2^53,10)=15.95...  I.e. almost, but not quite, 16 digits.
> Close enough, though, that tha vagaries of decimal notation
> don't allow you to distinguish in all cases between two different
> values. I.e. you can't even achieve (1) with "%g.16".

Okay, fine, 17 digits. That was simply a mistake on the part of my
memory; I hadn't gone and looked up the right answer and I remembered
wrong.

While it's true that not all numbers printed with 17 decimal digits
can be accurately represented by a double, the converse is false --
that is, while tostring(tonumber(x)) can't be a guaranteed round-trip,
tonumber(tostring(x)) CAN be, by making tostring() output enough
digits.

> The valid question, IMHO, should rather be: why does Lua not
> have a variable called say 'string.numformat' which is initialiized
> to "%.15g" but over which the user has control? But to this
> question the answer is easy: because Lua already allows
>
> local oldtostring = tostring
> tostring = function(x) if type(x)=='number'
>    then return string.format("%.16g".x)
>    else return oldtostring(x)
> end end

And this is of course a perfectly valid concept, but that doesn't
change the fact that tostring() really OUGHT to output enough digits
to ensure a clean round trip. Since it's not only possible but trivial
to do so, and since tostring() is the closest thing Lua has to
built-in serialization, doesn't it stand to reason that it SHOULD?

/s/ Adam