开发者

Storing floats in NSMutableArray gives unexpected results

I am writing a method which calculates the average time interval between a series of events (specifically, button tapping in iPhone). Since the number of time intervals I want to average might change during the program's life-cycle, I am storing the time readings in an object named tapTimes of type NSMutableArray so I don't have to worry about managing the array size.

When I store the time readings as doubles, everything works ok (for sim开发者_JAVA百科plicity, in the following example I am interested only in one time interval):

CFAbsoluteTime time = CFAbsoluteTimeGetCurrent();
[tapTimes addObject:[NSNumber numberWithDouble:(double)time]];
[tapTimes removeObjectAtIndex:0];
double deltaT = [[tapTimes objectAtIndex:1] doubleValue] - [[tapTimes objectAtIndex:0] doubleValue];

Which, for tapping every second or so, gives (the first value is just the first time reading since the array is initialized with zeros):

deltaT 311721948.947153
deltaT 1.023200
deltaT 1.080004
deltaT 1.055961
deltaT 1.087942
deltaT 1.080074

However, if I store floats:

CFAbsoluteTime time = CFAbsoluteTimeGetCurrent();
[tapTimes addObject:[NSNumber numberWithFloat:(float)time]];
[tapTimes removeObjectAtIndex:0];
float deltaT = [[tapTimes objectAtIndex:1] floatValue] - [[tapTimes objectAtIndex:0] floatValue];

Then I get unexpected results for deltaT:

deltaT 311721760.000000
deltaT 0.000000
deltaT 0.000000
deltaT 0.000000
deltaT 0.000000
deltaT 32.000000
deltaT 0.000000
deltaT 0.000000
deltaT 0.000000

Any idea what goes wrong? (I am doing mt first steps in Objective-c/cocoa, so I hope the answer is not too trivial :))


The problem is that float is not precise enough to tell one timestamp from a timestamp a second later. Stick to double; there's a reason that CFAbsoluteTime uses that type.

Here's a demonstration of the problem under 64-bit 10.6.4:

val: 311721760.000000 - val2: 311721761.000000 - (val2 - val): 1.000000
v: 311721760.000000 - v2: 311721760.000000 - (v2 - v): 0.000000

The first line used double values; val2 was generated by adding 1 to val. The second line used float values. The source code follows:

//clang so_float.m -o so_float
#import <stdio.h>

int
main(void) {
  double val = 311721760.000000;
  double val2 = val + 1.0;
  fprintf(stderr, "val: %f - val2: %f - (val2 - val): %f\n", val, val2, val2 - val);
  float v = val;
  float v2 = val + 1.0;
  fprintf(stderr, "v: %f - v2: %f - (v2 - v): %f\n", v, v2, v2 - v);
  return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜