I've read about the difference between double precision and single precision. However, in most cases, float
and double
seem to be interchangeable, i.e. using one or the other does not seem to affect the results. Is this really the case? When are floats and doubles interchangeable? What are the differences between them?
Float vs Double – Differences Between Float and Double in C++
c++floating-pointieee-754precision
Best Answer
Huge difference.
As the name implies, a
double
has 2x the precision offloat
[1]. In general adouble
has 15 decimal digits of precision, whilefloat
has 7.Here's how the number of digits are calculated:
This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.
while
Also, the maximum value of float is about
3e38
, but double is about1.7e308
, so usingfloat
can hit "infinity" (i.e. a special floating-point number) much more easily thandouble
for something simple, e.g. computing the factorial of 60.During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.
Of course, sometimes, even
double
isn't accurate enough, hence we sometimes havelong double
[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should useint
or a fraction class.Furthermore, don't use
+=
to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, usefsum
. Otherwise, try to implement the Kahan summation algorithm.[1]: The C and C++ standards do not specify the representation of
float
,double
andlong double
. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM)float
is indeed a IEEE single-precision floating point number (binary32), anddouble
is a IEEE double-precision floating point number (binary64).