iPhone /目标C - 比较双打不工作 [英] iphone / Objective C - Comparing doubles not working
问题描述
counter和interval都是双打。加速度计上发生这种情况:以(.01)为间隔进行加速度计算。 柜台最终应该增加到间隔。出于某种原因,我不能得到这个如果是真实的。
我可以忽略一些东西吗?
double interval = .5;
if(counter == interval){//最终应该是.50000 == .50000
NSLog(@Hit!);
[self playSound];
counter = 0;
} else {
counter + = .01;
NSLog(@%f,%f,%d,counter,interval,(counter == interval));
他们可能看起来是相同的有意义的数字你正在审查,但计算机看到更多。
为此,基金会框架提供不同类型的epsilon值如浮动和双。如果两个数字之间的距离小于epsilon,则可以假设这两个数字是相等的。
在您的情况下,您可以按如下方式使用它:
$ b $
- (BOOL)firstDouble:(double)first isEqualTo:(double)second {
if(fabs(first - second)< ; DBL_EPSILON)
return YES;
else
return NO;
$ / code>
或者在Swift 4中:
func doublesAreEqual(first:Double,second:Double) - > Bool {
如果晶圆厂(第一秒)< .ulpOfOne {
return true
}
return false
}
两个非常有用的链接:
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 eventually increment to "interval". For some reason i cant get this "if" to ring true.
Am I overlooking something?
double interval = .5;
if( counter == interval ){ //should eventually be .50000 == .50000
NSLog( @"Hit!" );
[self playSound];
counter = 0;
}else{
counter += .01;
}
NSLog( @"%f, %f, %d",counter,interval,(counter == interval) );
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
Friday Q&A 2011-01-04: Practical Floating Point
这篇关于iPhone /目标C - 比较双打不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!