Explain this floating point behavior

前端 未结 6 2188
野的像风
野的像风 2020-12-21 18:30

Please explain why the following pieces of code behave differently.

#include
int main(){
 float a=0.1;
 if(a<0.1)
  printf(\"less\");
 else         


        
6条回答
  •  再見小時候
    2020-12-21 18:57

    You cannot use comparison operators on floating point numbers reliably.

    A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.

    Something like:

    #include < math.h >
    if(fabs(a - b) <= accurary_threshold * fabs(a))
    

    Good Read:

    • What Every Computer Scientist Should Know About Floating-Point Arithmetic
    • Comparing Floating Point Numbers

提交回复
热议问题