lua-users home
lua-l archive

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




On 20/06/2023 14:43, Mouse wrote:
But if your hands are tied with JSON or similar formats - or you want
human-readability - you need to format as decimal.  This can't be
exact, [...]

It most certainly can.

Infinities and NaNs excepted, every IEEE float value can be represented
exactly as a sum of no more than 53 (or is it 54? I'd have to go check;
something <60, at any rate) powers of two.  And every power of two has
an exact decimal representation.  And, of course, the sum of a finite
number of exact decimal representations is also exact.

Of course, if the float's exponent is large, either large and positive
or large and negative, the exact decimal representation may be rather
lengthy.  But it exists.

/~\ The ASCII				  Mouse
\ / Ribbon Campaign
  X  Against HTML		mouse@rodents-montreal.org
/ \ Email!	     7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B

That's true and there's a proof of that in the link I posted before:

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html.

The problem is that the algorithm to convert the decimal representation into the internal binary representation is sometimes buggy or assumes some specific rounding behavior of the underlying FPU (behavior that can be assumed wrong or can be changed because of FP flags, at least in the ubiquitous IEEE754 standard).

That's the other link I already posted that highlights this problem:

https://www.exploringbinary.com/hexadecimal-floating-point-constants/

So in the end the actual implementation of C strod function, or whatever the system does to convert from a decimal string representation to the internal binary representation, cannot be trusted in practice (unless one has access to source code and can vet the algorithm) when absolute round-trip conversion accuracy is needed.

That's why the "%a" format was introduced in C99 together as the hexadecimal float literal syntax (e.g. 0x1.2p3).

See:
https://en.cppreference.com/w/c/language/floating_constant

-- Lorenzo