lua-users home
lua-l archive

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


On 14/03/2012 5:14 PM, Dirk Laurie wrote:
Beyond the issue of finite floating point precision, there is also the
non-trivial issue of converting losslessly between strings and floats.
...
I would have expected a conversion from "0.1" to double and back
to string to be lossless, even when printing extra digits.

The nontriviality is the same as converting noiselessly between inches
and centimetres.  Suppose we're allowed to go down to 1/256 of an
inch or 0.01mm.  Almost always, since those units are very close,
the conversion back and forth is lossless.  But only almost, since
"very close" is not "the same".

When one says "%.17f", the unit is 10^(-17), whereas the unit for
numbers between 0.125 and 0.25 in IEEE double is about 2.5 times that.

Out of curiosity, how does Lua perform its float<->string conversions?
...
Does Lua depend on (often poor) native sprintf implementations? or does it
use some variant of David Gay's fp routines?

In lconfig.h:

#define lua_number2str(s,n)     sprintf((s), LUA_NUMBER_FMT, (n))
...
#define lua_str2number(s,p)     strtod((s), (p))

Which means, Lua does depend on your C library, but you are just two
defines away from replacing it by your own choice.

I admit a large degree of ignorance here, but I have read the papers
cited below.

Those papers were very topical and necessary when they appeared back
in the early 90's when C89 wasn't even called that yet and very few
C compilers were standard-compliant.  Did you see David Gay's reference
to VAX arithmetic?

If you think this is irrelevant today, I'm afraid that you're out of touch. This is still a problem with modern C/C++ compilers, because unlike some other languages, requirements for float-string conversions were not originally standardised in C.


Nowadays even you-know-who has quite a decent compiler, even if it is
"um saco mesmo" in comparison to Gnu C.

I'm using Visual C++ 2005 and its conversions are definitely buggy compared to Gay's code. I can't speak for more recent Microsoft compilers. I switched to using Gay's code in my app a few years ago after wrestling with MSVC issues. Mozilla uses Gay's code, and the Javascript spec (for example) requires conversions to be reversible (as per the papers I linked to). As far as I know, C89 places no requirements on the losslessness of float-int conversions -- I'm not up with more recent versions.

For a relatively recent analysis of float-string errors in MSVC see:
http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/

Not that any of this is super-relevant to Lua, due to its "as buggy as the platform" design, I was just curious whether Lua made stronger guarantees than C (which makes none afaik).

Ross.