c3d / xl

A minimalist, general-purpose programming language based on meta-programming and parse tree rewrites
GNU General Public License v3.0
270 stars 15 forks source link

Treat float literals as decimal float literals and not as binary float literals #47

Open dumblob opened 3 years ago

dumblob commented 3 years ago

With decimal float literals finally making it into C23 (implemented 2021 and formally adopted in 2022) and seeing XL making significant changes in its basics incl. float literals, I'd like to propose making decimal float literals the default in XL. C++ already has decimal floats as an optional extension since 2011 if I'm not mistaken.

To use binary float literals (e.g. to double the performance and unpredictably lose precision) one can easily cast a decimal float literal to a binary one. Note, it's impossible to do the other way around (cast a decimal float lit. to a binary float lit.) if we wanted to maintain the precision the user wrote the float literal with.

c3d commented 3 years ago

Interesting idea. I wonder if the problem is not what default representation for real, ie should it be binary or decimal. Note that decimal FP has other issues (e.g. correct rounding I believe is more difficult).

dumblob commented 3 years ago

I wonder if the problem is not what default representation for real, ie should it be binary or decimal.

I'd definitely go also for decimal FP as I feel it must not be "worse than float". But thinking of it there are at least two ideas to explore:

1) real could actually be made even closer to mathematical notation used "on a paper" by introducing something like a "variable" decimal FP in a sense that one would choose beforehand how many "true" significant digits incl. zeros (not to be confused with decimal places nor with "usual" significant digits) should be used for output (e.g. a literal 1.500 would have 4 significant digits, 0001.500 would have 4 significant digits, 300 -> 3 sigdigits, 0.000100 -> 7 sigdigits) and internally a higher precision would be used to account for few rounding errors whereas float would stay compatible with IEEE 754 and thus support only _Decimal32 _Decimal64 _Decimal128 variants under the hood.

2) leave float as binary floating point and make only real into decimal floating point (possibly with the significant digits extension for better user experience and output purposes)

Note that decimal FP has other issues (e.g. correct rounding I believe is more difficult).

Could you be more specific? It still has infinity (actualy many infinities and both negative and positive ones) but otherwise most (if not all) of the issues I know of are basically gone. Actually correct rounding of decimal FP is one of the reasons why decimal FP is being used over binary FP. Feel free to take a look at the "best" library emulating decimal FP to see how rounding is being done (btw. mpdecimal is being used also by Python etc.).