Solution to float floating point type error


First of all, we must know that there are errors in floating point numbers.

For example:

    float f = 1;
    float sum = 0;
    for(int i=0; i<4000000; i++)
    {
        sum += f;
    }
    cout<<sum<<endl;


The output is: 9998.56


This is caused by the limited precision of the computer to save floating-point numbers, so how should we better avoid floating-point errors?

In fact, this kind of floating-point error occurs more often only when judging whether two floating-point numbers are equal.

Solution:

bool equal(double a,double b){
    return fabs(a-b)<0.000001;
}


As long as the difference between two floating-point numbers is small, they can be judged to be equal.


————————————————
Original link: https://blog.csdn.net/weixin_37609825/article/details/79810018

Guess you like

Origin blog.csdn.net/weixin_42565127/article/details/130888224