Cannot use = = to determine two floating-point numbers equal

Source: Internet
Author: User

When judging whether the two floating-point numbers A and B are equal, do not use a==b, you should determine the absolute value of the difference between the two
Fabs (A-B) is less than a threshold value, such as 1e-9.

////When judging whether the two floating-point numbers A and B are equal, do not use a==b, you should determine the absolute value of the difference between the two////fabs (A-B) is less than a threshold value, such as 1e-9. //#include <stdio.h>//#include <math.h>//#define EPSILON 0.000001//int main ()//{//float i;//    //dead Loop//    //For (i = 0; i = ten; i + = 0.4)//    //{//    //printf ("%.11f\n", I);//    //}//    //stop near the 10//For (i = 0;!) (Fabs (I-10) < EPSILON); i + = 0.4)//    {//printf ("%.11f\n", I);//    }////printf ("%.11f\n", I);////return 0;//}#include<stdio.h>#include<math.h>#defineEPSILON 1e-6//Program output://A + b! = 0.7//FA + fb = = 0.7//Please press any key to continue ...intMain () {floatA =0.3; floatb =0.4; floatc = A +b; if(c = =0.7) printf ("A + b = = 0.7\n"); Elseprintf ("A + b! = 0.7\n"); floatFA =0.3; floatFB =0.4; floatFC = FA +FB; if(Fabs (FC-0.7) <EPSILON) printf ("FA + fb = = 0.7\n"); Elseprintf ("FA + fb! = 0.7\n"); return 0;}

As can be seen from the program, because the IEEE floating-point standard indicates that data precision is limited, floating-point operations can easily cause small errors, so you cannot use the equal sign to determine whether the floating-point numbers are equal.

Cannot use = = to determine two floating-point numbers equal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.