MATLAB: Does adding time directly to datenum not add the anticipated amount of time

datenumtime

Matlab time is stored as a numerical value in units of days since 00-Jan-0000. Going on this premise, why is it that when I add 1/1400 (the value of one minute as there are 1400 minutes in a day) that occasionally I will lose a second.
For example
mytime = datenum('03-04-2015','mm-dd-yyyy'); % mytime should equal 736027
If I systematically add 1/1400 to this datenum (the value of one minute as there are 1400 minutes in a day), the time will not change minute by minute. This can be shown easily with the following loop.
for i = 1:1440
mytime = mytime + 1/1440;
if ~strcmp(datestr(mytime,'SS'),'00')
disp(i)
disp(datestr(mytime,'dd-mm-yyyy HH:MM:SS')
break
end
end
On the 137th iteration, a full second is dropped. I can effectively add time using the datenum or minutes function, setting it to one minute and adding that, but it takes significantly longer and isn't especially efficient. I'm working with a large amount of data and adding time using this method makes my program run way too slow. Why is this happening and how can I get around it without crippling my runtime?

Best Answer

Most likely 1/1440 can not be represented exactly in binary, so every time you add it, you've got a small rounding error. These rounding errors accumulate to the point you loose a second after a while.
It's a fact that fractions can not be represented exactly by a computer (using double) so you should avoid summing small numbers. Note for example that:
s = 0
for i = 1:10, s = s + 0.1 end
s == 1
returns false due to the accumulation error after just 10 iterations.
What about using date vectors (or datetime) instead of datenum? They both use integer representation for hours, minutes and seconds.