First of all, this is not a floating point newbie question. I know results of floating point arithmetic (not to mention transcendental functions) usually cannot be represent
Well being no floating point expert myself, I'd defer to using a well tested open source library.
The GNU MPFR is a good one.
The MPFR library is a C library for multiple-precision floating-point computations with correct rounding. The main goal of MPFR is to provide a library for multiple-precision floating-point computation which is both efficient and has a well-defined semantics.
sprintf and similar functions are usually only specified up to a number of significant digits to uniquely determine the original floating point value; they don't necessarily print the exact decimal representation.
You can ask for more significant digits than the default:
printf("%.100g\n", 0.1);
prints 0.1000000000000000055511151231257827021181583404541015625
.
If you want more exact results, why not use fixed point math instead? Conversions are quick. Error is known and can be worked around. Not an exact answer to your question, but a different idea for you.
I see you’ve accepted an answer already, but here are a couple of open source implementations of this conversion you might want to look at:
David Gay’s dtoa()
function in dtoa.c
: http://www.netlib.org/fp/dtoa.c.
The function ___printf_fp()
in the /stdio-common/printf_fp.c
file in Glibc (http://ftp.gnu.org/gnu/glibc/glibc-2.11.2.tar.gz, for example).
Both will print as many digits as you ask for in a %f
-type printf
, as I’ve written about at: