-1

So I understand the difference for floats vs doubles in C++.

A double is simply a double float point whereas a float a single floating point (double the size of precision).

My question is, how come floats are represented as '300000011920928955078125e-24' (for the value 3.0) but a double will simply be shows as 3.0?

Why wouldn't a double display all the trailing digits? It has a higher precision but also still suffers from the same finite precision as floating point, so I'm not sure why it doesn't also show up like that.

Setheron
  • 3,520
  • 3
  • 34
  • 52

1 Answers1

2

That's because many values cannot be represented precisely in floating point (either single or double precision), but double can represent something much much closer. If you print with more decimal places shown, you'll almost certainly see the error.

The value 0.3 cannot be represented precisely. Additionally, the result of a calculation might pick up error from the operands. "0.3 * 10" will magnify the error in the result, so will no be precisely 3.0.

The best analogue is trying to display "1/3" in decimal. You might write it 0.333333, or 0.333333333333. If you multiply those by 3, you'll get 0.999999 or 0.999999999999. Displaying those on a calculator screen (which has a fixed number of digits), the first will be shown with the error, while the second will get rounded up.

Edit: Code to demonstrate this:

#include <stdio.h>

int main()
{
    float f = 0.3;
    double d = 0.3;
    printf("%.50lf %.50lf\n", f, d);
    printf("%.10lf %.10lf\n", f, d);
}

Displays:

0.30000001192092895507812500000000000000000000000000 0.29999999999999998889776975374843459576368300000000
0.3000000119 0.3000000000
Martin
  • 3,703
  • 2
  • 21
  • 43