c++ incorrect floating point arithmetic

前端 未结 3 1043
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 13:07

For the following program:

#include 
#include 
using namespace std;
int main()
{
    for (float a = 1.0; a < 10; a++)
              


        
3条回答
  •  遥遥无期
    2020-12-06 13:55

    There are a lot of numbers that computers cannot represent, even if you use float or double-precision float. 1/3, or .3 repeating, is one of those numbers. So it just does the best it can, which is the result you get.

    See http://floating-point-gui.de/, or google float precision, there's a ton of info out there (including many SO questions) on this subject.

    To answer your questions -- yes, this is an inherent limitation in both the float class and the double class. Some mathematical programs (MathCAD, probably Mathematica) can do "symbolic" math, which allows calculation of the "correct" answers. In many cases, the round-off error can be managed, even over really complex computations, such that the top 6-8 decimal places are correct. However, the opposite is true as well -- naive computations can be constructed that return wildly incorrect answers.

    For small problems like division of whole numbers, you'll get a decent number of decimal place accuracy (maybe 4-6 places). If you use double precision floats, that will go up to maybe 8. If you need more... well, I'd start questioning why you want that many decimal places.

提交回复
热议问题