Skip to main content

numerics - The algorithm behind InputForm for machine numbers


There are several questions on this site about implementing fast CSV/TSV export for machine numbers without loss of precision. Recently I discovered that Export merely applies ToString[#, InputForm] & to every number in the table for conversion it into a string:


Trace[ExportString[{-7756.0224337393065}, "TSV"], ToString] // Flatten


{ToString[-7756.0224337393065, InputForm], "-7756.0224337393065"}


Unfortunately there seems to be no built-in alternative to InputForm in Mathematica for obtaining the correct digits of machine numbers, even RealDigits isn't precise:


x = 44802.395880518656;
ToExpression@ToString[x, InputForm] - x
FromDigits@RealDigits[x] - x


0.

-7.27596*10^-12


InputForm works correctly but very slow. From the other hand, it shouldn't be too difficult to re-implement the algorithm behind this conversion as a compilable function in order to get huge speed-up.


Does anybody know what the algorithm is? Probably it isn't proprietary and can be found in the literature.




Comments