Search code examples
cdoublefloating-accuracyadditionexponential

C: Adding Exponentials


What I thought was a trivial addition in standard C code compiled by GCC has confused me somewhat.

If I have a double called A and also a double called B, and A = a very small exponential say 1e-20 and B is a larger value for example 1e-5 - why does my double C which equals the summation A+B take on the dominant value B? I was hoping that when I specify to print to 25 decimal places I would get 1.00000000000000100000e-5.

Instead what I get is just 1.00000000000000000000e-5. Do I have to use long double or something else?

Very confused, and an easy question for most to answer I'm sure! Thanks for any guidance in advance.


Solution

  • Yes, there is not enough precision in the double mantissa. 2^53 (the precision of the double mantissa) is only slightly larger than 10^15 (the ratio between 10^20 and 10^5) so binary expansion and round off can easily squash small bits at the end.

    http://en.wikipedia.org/wiki/Double-precision_floating-point_format

    Google is your friend etc.