NSDate and double precision problem

Here is the code

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); 

output

Interval: 32.456000 32.456000 32455.999970 32456.000000

Why does NSDate return a value that will lose some fixes?

+4
source share
1 answer

This is not a problem for NSDate itself. This is the nature of the floating point numbers themselves. I believe that NSDate kept its date from the OS X (2001) era, not the UNIX era (1970). Let the difference of two epochs be equal to x.

Then the following will happen:

 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 

However, the floating point does not have infinite accuracy. So, +x , and then -x may introduce a small error into the calculation.

For more information, see this Wikipedia article.

If you are using the OS X era, you get what you naively expect:

 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. 
+7
source

Source: https://habr.com/ru/post/1332306/


All Articles