NSNumber比较:返回不同的结果 [英] NSNumber compare: returning different results
问题描述
我正在尝试进行一些数字比较,我得到了一些奇怪的结果。
I'm trying to do some number comparisons and I'm getting some weird results.
NSNumber* number1 = [NSNumber numberWithFloat:1.004];
NSNumber* number2 = [NSNumber numberWithDouble:1.004];
([number1 compare:number2] == NSOrderedSame) ? NSLog(@"YES") : NSLog(@"NO");
([number1 compare:number2] == NSOrderedAscending) ? NSLog(@"YES") : NSLog(@"NO");
([number1 doubleValue] == [number2 doubleValue]) ? NSLog(@"YES") : NSLog(@"NO");
([number1 floatValue] == [number2 floatValue]) ? NSLog(@"YES") : NSLog(@"NO");
日志输出:
否
是
b $ b否
是
NO
YES
NO
YES
<这对我来说非常令人沮丧。我知道这可能是因为浮点数与双精度数之间的差异。在我看来,它正在将双倍缩减到浮点数来进行比较。但如果我不知道如何创建数字,我如何得到正确的结果?是否有不同的方法来比较NSNumber?
This is extremely frustrating to me. I know this is probably because the difference between the number of bits in a float compared to a double. It seems to me it's truncating the double down to a float to do the compare. But if I don't know how the number is created, how do I get the correct results? Is there a different way to compare NSNumber's?
推荐答案
我尝试使用 isEqualToNumber:
它返回NO。它们不相同的原因是因为1.004不能完全用二进制表示。 double
近似值在小数点后面的位数多于 float
近似值,因此两个数字不同。通常,在比较浮点数时,您要测试它们是否等于容差值 fabs(a - b)<容差
:
I tried using isEqualToNumber:
and it returned NO. The reason they aren't the same is because 1.004 can't be represented exactly in binary. The double
approximation has more digits after the decimal point than the float
approximation so the two numbers are different. Normally, when comparing floating point numbers, you test to see if they are equal to within a tolerance value fabs(a - b) < tolerance
:
NSNumber* number1 = [NSNumber numberWithFloat:1.004];
NSNumber* number2 = [NSNumber numberWithDouble:1.004];
NSLog(@"number 1: %.12f", [number1 doubleValue]);
NSLog(@"number 2: %.12f", [number2 doubleValue]);
([number1 isEqualToNumber:number2]) ? NSLog(@"YES") : NSLog(@"NO");
fabs([number1 floatValue] - [number2 doubleValue]) < 1.0e-7 ? NSLog(@"YES") : NSLog(@"NO");
结果:
2012-02-09 15:08:34.272 so9219935[3313:903] number 1: 1.003999948502
2012-02-09 15:08:34.274 so9219935[3313:903] number 2: 1.004000000000
2012-02-09 15:08:34.275 so9219935[3313:903] NO
2012-02-09 15:08:34.275 so9219935[3313:903] YES
这篇关于NSNumber比较:返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!