Strange results with floating-point comparison

后端 未结 10 1753
余生分开走
余生分开走 2020-12-10 08:34

I have this simple test:

double h;
...
// code that assigns h its initial value, used below
...
if ((h>0) && (h<1)){
 //branch 1 -some computati         


        
10条回答
  •  生来不讨喜
    2020-12-10 09:39

    Check the actual value of h by printing it out with maximum precision. You'll probably find that it is actually slightly less than 1.0.

    I ran the following code as a test

    #include 
    
    int main()
    {
        double h = 1.0;
        if((h>0) && (h<1))
        {
            std::cout << "first branch" << std::endl;
        }
        else
        {
            std::cout << "second branch" << std::endl;
        }
    }
    

    and the output was "first branch" (using g++ 4.3.2 on Ubuntu 8.10), but Indeera mentioned in a comment that the same code running on Windows XP compiled with VS2005 gives the output "second branch" (thanks, Indeera).

    You might change your code to compare the differences between h and 0.0 and h and 1.0 to some small delta value.

    double allowedDelta = 0.000001;
    
    if( ((h - 0.0) > allowedDelta) && ((1.0 - h) > allowedDelta) )
    ... // h is between 0.000001 and 0.9999990
    

    Note that "(h - 0.0)" can be replaced with "h" in this special case. I'm leaving it the way it is for illustrative value.

    Also note that if you were only making one comparison you'd need to compare the delta to the absolute value of the difference between h and some constant. Since you're checking a range here, the two comparisons ANDed together make a special case where you can bypass the use of abs. If h is a negative value or some positive value greater than 1.0 it will be out of range and fail one of the two tests above.

提交回复
热议问题