MATLAB: Datenum Generating different numbers for same time difference

datenum

I have following two date time data points, and I am taking difference of them :
diff_55mins2=abs(datenum('01-04-2017 07:00:00','dd-mm-yyyy HH:MM:SS')-datenum('01-04-2017 07:55:00','dd-mm-yyyy HH:MM:SS'))
diff_55mins1=abs(datenum('01-04-2017 05:00:00','dd-mm-yyyy HH:MM:SS')-datenum('01-04-2017 05:55:00','dd-mm-yyyy HH:MM:SS'))
If you see, both the above code lines are trying to find difference between two date time stamp. The difference is 55 minutes for the both, however after conversion using datenum, there is difference in the numbers as following:
diff_55mins2 =
0.038194444496185
diff_55mins1 =
0.038194444379769
Why there is such difference? They are essentially corresponding to 5 minutes difference in time. Can anyone please explain it.
Thankyou in advance!

Best Answer

FP roundoff; datenum just uses a double for the time serial value; the integer portion is days and the fractional part the fractional portion of the day in seconds. It is susceptible to all the vagaries of fp arithmetic....
>> dn2=abs(datenum('01-04-2017 07:00:00','dd-mm-yyyy HH:MM:SS')-datenum('01-04-2017 07:55:00','dd-mm-yyyy HH:MM:SS'))
dn2 =
0.0382
>> dn1=abs(datenum('01-04-2017 05:00:00','dd-mm-yyyy HH:MM:SS')-datenum('01-04-2017 05:55:00','dd-mm-yyyy HH:MM:SS'))
dn1 =
0.0382
>> dn2-dn1
ans =
1.1642e-10
>> ans*24*60*60
ans =
1.0058e-05
>>
So the difference between the two values isn't zero but is about 10 usec or in absolute terms
>> dn=datenum('01-04-2017 05:00:00','dd-mm-yyyy HH:MM:SS')
dn =
7.3679e+05
>> eps(dn)
ans =
1.1642e-10
or the closest can get to the difference in floating point for the size of the variable; iow, a double just can't be any more precise than the result obtained.
To see how close in minutes,
>> format longg
>> dn2*24*60
ans =
55.0000000745058
>> dn1*24*60
ans =
54.9999999068677
>>
Use the new-fangled datetime class instead; it's implemented as an object and has much more precision...
>> fmtDT='dd-MM-yyyy HH:mm:ss'; % a little shorthand; the formatting is different, too...
>> dt1=abs(datetime('01-04-2017 05:00:00','inputformat',fmtDT)-datetime('01-04-2017 05:55:00','inputformat',fmtDT))
dt1 =
duration
00:55:00
>> dt2=abs(datetime('01-04-2017 07:00:00','inputformat',fmtDT)-datetime('01-04-2017 07:55:00','inputformat',fmtDT))
dt2 =
duration
00:55:00
>> dt1==dt2
ans =
logical
1
>>
and the two are identical.
There are many other enhancements with datetime as well that for almost everything now they are the preferred way to handle time.