iphone / Objective C - Comparing doubles not working

后端 未结 2 1177
庸人自扰
庸人自扰 2020-12-03 17:53

I think I\'m going insane. \"counter\" and \"interval\" are both doubles. This is happening on accelerometer:didAccelerate at an interval of (.01) . \"counter\" should even

2条回答
  •  执笔经年
    2020-12-03 18:35

    Don't ever compare doubles or floats with equality - they might look the same at the number of significant figures your are examining but the computer sees more.

    For this purpose, the Foundation Framework provides "epsilon" values for different types such as "float" and "double". If the distance between two numbers is smaller than epsilon, you can assume these two numbers are equal.

    In your case, you would use it as follow:

    - (BOOL)firstDouble:(double)first isEqualTo:(double)second {
        if(fabs(first - second) < DBL_EPSILON)
            return YES;
        else
            return NO;
    }
    

    Or in Swift 4:

    func doublesAreEqual(first: Double, second: Double) -> Bool {
        if fabs(first - second) < .ulpOfOne {
            return true
        }
        return false
    }
    

    Two very useful links:

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Interesting discussion of Unit in Last Place (ULP) and usage in Swift

    Friday Q&A 2011-01-04: Practical Floating Point

提交回复
热议问题