4 ms·
If you require the output to be the shortest possible (e.g. 0.1+0.11 should print as “0.21”, not as “0.21000000000000002”) and to have your output round-trip (i
by Someone 8y ago
If you require the output to be the shortest possible (e.g. 0.1+0.11 should print as “0.21”, not as “0.21000000000000002”) and to have your output round-trip (if you read in what you printed, you get back the number you printed) I would think printing floating point numbers is harder than writing a pretty-printer.
Pretty-printers have the advantage never being finished, as there always are cases where some people would say “I would format that differently”. That’s an advantage because it also means you can declare any version that works decently “finished”. For formatting floats, it’s much more black or white. Your formatter either works or it is buggy.
The first working formatter for floating point numbers is from 1980, IIRC, and doing it correctly only became somewhat the expected case after Steelers 1990 paper (https://lists.nongnu.org/archive/html/gcl-devel/2012-10/pdfkieTlklRzN.pdf https://lists.nongnu.org/archive/html/gcl-devel/2012-10/pdfk...)
- jancsika 8y ago> and to have your output round-trip Unless you're simply talking about round-trip within the application itself, that's not possible.
- tlb 8y agoIt is possible, and most reasonable format systems guarantee it. Javascript guarantees that parseFloat(x.toString()) === x for any fp number x. The same extends to JSON formatting. Python guarantees that eval(str(x)) == x.
- jancsika 8y agoThat's because Javascript doesn't print out the shortest possible output. OP's requirement is that the output for 0.1 + 0.11 is displayed as 0.21, and that the output survives a round-trip. Your example satisfies the latter but not the former.
- kkylin 8y agoAnother example, more specialized than the others given, is MIT Scheme: IIRC it guarantees that when you READ back a float written by WRITE, you get the same float back, bit for bit.
- userbinator 8y agoGetting a floating point number printed "exactly" (as in with full precision, not necessarily what people expect) is not very hard; the tricky part is, as you mention, having the shortest possible representation and rounding it correctly, as well as making it efficient.
- bradleyjg 8y agoYou need to find the shortest number that’s closer to your target float than any other float. Then to go the other direction you just find the nearest float.