4

ここにコードがあります

NSDate* d = [NSDate dateWithTimeIntervalSince1970:32.4560];
double ti = [d timeIntervalSince1970];
NSLog(@"Interval: %f %f %f %f",ti,32.4560,ti*1000.0,32.4560*1000.0);

出力は

間隔: 32.456000 32.456000 32455.999970 32456.000000

NSDate が一部の精度を失う値を返すのはなぜですか?

4

1 に答える 1

7

それ自体は問題ではありませんNSDate。それは浮動小数点数自体の性質にあります。NSDateUNIX エポック (1970) ではなく、OS X エポック (2001) からの日付を保持していると思います。2 つのエポックの差を x とします。

次に何が起こるかは次のとおりです。

NSDate* d = [NSDate dateWithTimeIntervalSince1970:32.4560];
// at this point, d keeps 32.4560 + x
double ti = [d timeIntervalSince1970];
// ti is then (32.4560+x)-x

ただし、浮動小数点の精度は無限ではありません。そのため、計算にわずかな誤差が生じる可能性があります+x-x

詳細については、このウィキペディアの記事などをお読みください。

OS X エポックを使用すると、素朴に期待するものが得られます。

NSDate* d = [NSDate dateWithTimeIntervalSinceReferenceDate:32.4560];
// at this point, d keeps 32.4560 + 0
double ti = [d timeIntervalSinceReferenceDate];
// ti is then (32.4560+0)-0, which is 32.4560 even in the floating point world.
于 2010-12-16T05:36:22.307 に答える