How dangerous is it to compare floating point values?

前端 未结 11 798
囚心锁ツ
囚心锁ツ 2020-11-21 06:44

I know UIKit uses CGFloat because of the resolution independent coordinate system.

But every time I want to check if for example fram

相关标签:
11条回答
  • 2020-11-21 06:48

    The last time I checked the C standard, there was no requirement for floating point operations on doubles (64 bits total, 53 bit mantissa) to be accurate to more than that precision. However, some hardware might do the operations in registers of greater precision, and the requirement was interpreted to mean no requirement to clear lower order bits (beyond the precision of the numbers being loaded into the registers). So you could get unexpected results of comparisons like this depending on what was left over in the registers from whoever slept there last.

    That said, and despite my efforts to expunge it whenever I see it, the outfit where I work has lots of C code that is compiled using gcc and run on linux, and we have not noticed any of these unexpected results in a very long time. I have no idea whether this is because gcc is clearing the low-order bits for us, the 80-bit registers are not used for these operations on modern computers, the standard has been changed, or what. I'd like to know if anyone can quote chapter and verse.

    0 讨论(0)
  • 2020-11-21 06:50

    First of all, floating point values are not "random" in their behavior. Exact comparison can and does make sense in plenty of real-world usages. But if you're going to use floating point you need to be aware of how it works. Erring on the side of assuming floating point works like real numbers will get you code that quickly breaks. Erring on the side of assuming floating point results have large random fuzz associated with them (like most of the answers here suggest) will get you code that appears to work at first but ends up having large-magnitude errors and broken corner cases.

    First of all, if you want to program with floating point, you should read this:

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Yes, read all of it. If that's too much of a burden, you should use integers/fixed point for your calculations until you have time to read it. :-)

    Now, with that said, the biggest issues with exact floating point comparisons come down to:

    1. The fact that lots of values you may write in the source, or read in with scanf or strtod, do not exist as floating point values and get silently converted to the nearest approximation. This is what demon9733's answer was talking about.

    2. The fact that many results get rounded due to not having enough precision to represent the actual result. An easy example where you can see this is adding x = 0x1fffffe and y = 1 as floats. Here, x has 24 bits of precision in the mantissa (ok) and y has just 1 bit, but when you add them, their bits are not in overlapping places, and the result would need 25 bits of precision. Instead, it gets rounded (to 0x2000000 in the default rounding mode).

    3. The fact that many results get rounded due to needing infinitely many places for the correct value. This includes both rational results like 1/3 (which you're familiar with from decimal where it takes infinitely many places) but also 1/10 (which also takes infinitely many places in binary, since 5 is not a power of 2), as well as irrational results like the square root of anything that's not a perfect square.

    4. Double rounding. On some systems (particularly x86), floating point expressions are evaluated in higher precision than their nominal types. This means that when one of the above types of rounding happens, you'll get two rounding steps, first a rounding of the result to the higher-precision type, then a rounding to the final type. As an example, consider what happens in decimal if you round 1.49 to an integer (1), versus what happens if you first round it to one decimal place (1.5) then round that result to an integer (2). This is actually one of the nastiest areas to deal with in floating point, since the behaviour of the compiler (especially for buggy, non-conforming compilers like GCC) is unpredictable.

    5. Transcendental functions (trig, exp, log, etc.) are not specified to have correctly rounded results; the result is just specified to be correct within one unit in the last place of precision (usually referred to as 1ulp).

    When you're writing floating point code, you need to keep in mind what you're doing with the numbers that could cause the results to be inexact, and make comparisons accordingly. Often times it will make sense to compare with an "epsilon", but that epsilon should be based on the magnitude of the numbers you are comparing, not an absolute constant. (In cases where an absolute constant epsilon would work, that's strongly indicative that fixed point, not floating point, is the right tool for the job!)

    Edit: In particular, a magnitude-relative epsilon check should look something like:

    if (fabs(x-y) < K * FLT_EPSILON * fabs(x+y))
    

    Where FLT_EPSILON is the constant from float.h (replace it with DBL_EPSILON fordoubles or LDBL_EPSILON for long doubles) and K is a constant you choose such that the accumulated error of your computations is definitely bounded by K units in the last place (and if you're not sure you got the error bound calculation right, make K a few times bigger than what your calculations say it should be).

    Finally, note that if you use this, some special care may be needed near zero, since FLT_EPSILON does not make sense for denormals. A quick fix would be to make it:

    if (fabs(x-y) < K * FLT_EPSILON * fabs(x+y) || fabs(x-y) < FLT_MIN)
    

    and likewise substitute DBL_MIN if using doubles.

    0 讨论(0)
  • 2020-11-21 06:51

    I want to give a bit of a different answer than the others. They are great for answering your question as stated but probably not for what you need to know or what your real problem is.

    Floating point in graphics is fine! But there is almost no need to ever compare floats directly. Why would you need to do that? Graphics uses floats to define intervals. And comparing if a float is within an interval also defined by floats is always well defined and merely needs to be consistent, not accurate or precise! As long as a pixel (which is also an interval!) can be assigned that's all graphics needs.

    So if you want to test if your point is outside a [0..width[ range this is just fine. Just make sure you define inclusion consistently. For example always define inside is (x>=0 && x < width). The same goes for intersection or hit tests.

    However, if you are abusing a graphics coordinate as some kind of flag, like for example to see if a window is docked or not, you should not do this. Use a boolean flag that is separate from the graphics presentation layer instead.

    0 讨论(0)
  • 2020-11-21 06:54

    [The 'right answer' glosses over selecting K. Selecting K ends up being just as ad-hoc as selecting VISIBLE_SHIFT but selecting K is less obvious because unlike VISIBLE_SHIFT it is not grounded on any display property. Thus pick your poison - select K or select VISIBLE_SHIFT. This answer advocates selecting VISIBLE_SHIFT and then demonstrates the difficulty in selecting K]

    Precisely because of round errors, you should not use comparison of 'exact' values for logical operations. In your specific case of a position on a visual display, it can't possibly matter if the position is 0.0 or 0.0000000003 - the difference is invisible to the eye. So your logic should be something like:

    #define VISIBLE_SHIFT    0.0001        // for example
    if (fabs(theView.frame.origin.x) < VISIBLE_SHIFT) { /* ... */ }
    

    However, in the end, 'invisible to the eye' will depend on your display properties. If you can upper bound the display (you should be able to); then choose VISIBLE_SHIFT to be a fraction of that upper bound.

    Now, the 'right answer' rests upon K so let's explore picking K. The 'right answer' above says:

    K is a constant you choose such that the accumulated error of your computations is definitely bounded by K units in the last place (and if you're not sure you got the error bound calculation right, make K a few times bigger than what your calculations say it should be)

    So we need K. If getting K is more difficult, less intuitive than selecting my VISIBLE_SHIFT then you'll decide what works for you. To find K we are going to write a test program that looks at a bunch of K values so we can see how it behaves. Ought to be obvious how to choose K, if the 'right answer' is usable. No?

    We are going to use, as the 'right answer' details:

    if (fabs(x-y) < K * DBL_EPSILON * fabs(x+y) || fabs(x-y) < DBL_MIN)
    

    Let's just try all values of K:

    #include <math.h>
    #include <float.h>
    #include <stdio.h>
    
    void main (void)
    {
      double x = 1e-13;
      double y = 0.0;
    
      double K = 1e22;
      int i = 0;
    
      for (; i < 32; i++, K = K/10.0)
        {
          printf ("K:%40.16lf -> ", K);
    
          if (fabs(x-y) < K * DBL_EPSILON * fabs(x+y) || fabs(x-y) < DBL_MIN)
            printf ("YES\n");
          else
            printf ("NO\n");
        }
    }
    ebg@ebg$ gcc -o test test.c
    ebg@ebg$ ./test
    K:10000000000000000000000.0000000000000000 -> YES
    K: 1000000000000000000000.0000000000000000 -> YES
    K:  100000000000000000000.0000000000000000 -> YES
    K:   10000000000000000000.0000000000000000 -> YES
    K:    1000000000000000000.0000000000000000 -> YES
    K:     100000000000000000.0000000000000000 -> YES
    K:      10000000000000000.0000000000000000 -> YES
    K:       1000000000000000.0000000000000000 -> NO
    K:        100000000000000.0000000000000000 -> NO
    K:         10000000000000.0000000000000000 -> NO
    K:          1000000000000.0000000000000000 -> NO
    K:           100000000000.0000000000000000 -> NO
    K:            10000000000.0000000000000000 -> NO
    K:             1000000000.0000000000000000 -> NO
    K:              100000000.0000000000000000 -> NO
    K:               10000000.0000000000000000 -> NO
    K:                1000000.0000000000000000 -> NO
    K:                 100000.0000000000000000 -> NO
    K:                  10000.0000000000000000 -> NO
    K:                   1000.0000000000000000 -> NO
    K:                    100.0000000000000000 -> NO
    K:                     10.0000000000000000 -> NO
    K:                      1.0000000000000000 -> NO
    K:                      0.1000000000000000 -> NO
    K:                      0.0100000000000000 -> NO
    K:                      0.0010000000000000 -> NO
    K:                      0.0001000000000000 -> NO
    K:                      0.0000100000000000 -> NO
    K:                      0.0000010000000000 -> NO
    K:                      0.0000001000000000 -> NO
    K:                      0.0000000100000000 -> NO
    K:                      0.0000000010000000 -> NO
    

    Ah, so K should be 1e16 or larger if I want 1e-13 to be 'zero'.

    So, I'd say you have two options:

    1. Do a simple epsilon computation using your engineering judgement for the value of 'epsilon', as I've suggested. If you are doing graphics and 'zero' is meant to be a 'visible change' than examine your visual assets (images, etc) and judge what epsilon can be.
    2. Don't attempt any floating point computations until you've read the non-cargo-cult answer's reference (and gotten your Ph.D in the process) and then use your non-intuitive judgement to select K.
    0 讨论(0)
  • 2020-11-21 07:06
    -(BOOL)isFloatEqual:(CGFloat)firstValue secondValue:(CGFloat)secondValue{
    
    BOOL isEqual = NO;
    
    NSNumber *firstValueNumber = [NSNumber numberWithDouble:firstValue];
    NSNumber *secondValueNumber = [NSNumber numberWithDouble:secondValue];
    
    isEqual = [firstValueNumber isEqualToNumber:secondValueNumber];
    
    return isEqual;
    

    }

    0 讨论(0)
  • 2020-11-21 07:07

    You can use such code for compare float with zero:

    if ((int)(theView.frame.origin.x * 100) == 0) {
        // do important operation
    }
    

    This will compare with 0.1 accuracy, that enough for CGFloat in this case.

    0 讨论(0)
提交回复
热议问题