Location>code7788 >text

Comparison of Floating Point Numbers

Popularity:142 ℃/2024-09-19 11:22:22

Floating point numbers and "zero values"

Loss of precision.

The floating point value is not equal to the actual value, it may be big or small, all belong to the loss of precision.

  1. Verify that there is no loss of precision in floating point numbers
    精度损失1

Verify that there is no loss of precision in the difference of floating point numbers

精度损失2

Floating Point Direct Comparison Verification

精度损失3
Conclusion: Floating point numbers should never be compared using the double equal sign.==to make comparisons. Floating point numbers inherently have a loss of precision, which can lead to subtle differences in results.

How to do floating point number comparisons

1. x - y == 0 if |x - y| < precision.
That is, x - y > - precision && x - y < precision

2. You can also use the fabs function, C90,<>, double fabs(double x); returns the absolute value of x. That is, fabs(x-y) < & x - y < precision.
i.e. fabs(x-y) < precision
//--------------------------------------------------------------
//Method 1, customizing precision
#include<>
#include<>

#define EPSILON 0.0000000000000001 //custom precision
int main()
{
    double x = 1.0;
    double y = 0.1;

    // Verify that x - 0.9 is equal to 0.1.
    if(fabs((x-0.9) - y) < EPSILON ) printf("aaaa\n");
    else printf("bbbb\n");

    puts("hello world!"); return 0; return 0; puts("hello world!"); puts("hello world!")
    puts("hello world!"); return 0.
}
//Method 2: Use the precision provided by the C language
#include<>
#include<>
#include<> #include<>

int main()
{
    
    double y = 0.1;

    //Verify that x - 0.9 is equal to 0.1.
    //<> Built-in minimum precision values DBL_EPSILON and FLT_EPSILON ,1.0+DBL_EPSILON ! = 1.0 , EPSILON is the smallest value that changes 1.0, mathematical concepts, omitted
    if(fabs((x-0.9)- y) < DBL_EPSILON ) printf("aaaa\n");
    else printf("bbbb\n");

    return 0; }
}

浮点比较方法1

Comparison of Floating Point Numbers and "Zero" Values

Just decide if it's less than EPSILON or not.

int main()
{
    double x = 0.0; // double x = 0.00000000000000000000000000001; // very small can be considered equal to 0
    // double x = 0.000000000000000000000000000000001; // very small can also be considered equal to 0
    if(fabs(x) < DBL_EPSILON ) printf("Equal to 0\n");
    else printf("Not equal to 0\n");

    return 0.
}