c++typesfloating-pointdouble-precision

Should I use double or float?


What are the advantages and disadvantages of using one instead of the other in C++?


Solution

  • If you want to know the true answer, you should read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

    In short, although double allows for higher precision in its representation, for certain calculations it would produce larger errors. The "right" choice is: use as much precision as you need but not more and choose the right algorithm.

    Many compilers do extended floating point math in "non-strict" mode anyway (i.e. use a wider floating point type available in hardware, e.g. 80-bits and 128-bits floating), this should be taken into account as well. In practice, you can hardly see any difference in speed -- they are natives to hardware anyway.