Why 'hour' function output and 'datestr' output is not matching?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jannatun Nahar
le 15 Juin 2017
Commenté : Peter Perkins
le 20 Juin 2017
I often use Matlab 'hour' and 'datestr' /'datenum' functions and it always worked fine. But recently at a specific time I found the following issue. I was using the time as 7.357206249999994e+05 for which 'datestr' gives correct ans but 'hour' didn't match.
>>datestr(7.357206249999994e+05)
ans =
'01-May-2014 15:00:00'
K>> hour(7.357206249999994e+05)
ans =
14
As you can see the hour didnt match in the datestr output and hour output, and most likely it is happening for rounding because hour(7.357206250000000e+05) gives ans 15. But since I get these time values through codes so how to deal with this round off in date tracking. I used the following code:
>>current_tim=datenum(datestr('01-May-2014 00:00:00'));
>> for k=1:24*7
[out]=function(theta_pre,weaData,current_tim,I(k));
current_tim=current_tim+datenum(0,0,0,1,0,0) ;%adding one hour in each loop
datestr(current_tim)%checking
hour(current_tim)%checking
end
0 commentaires
Réponse acceptée
Walter Roberson
le 15 Juin 2017
Yes, it is rounding. datenum('01-May-2014 15:00:00') is 735720.625 so anything that does not reach .625 after whatever internal rounding will convert to hour 14. Experimentally I find that the breakpoint is between 735720.625 * (1-35*eps) and 735720.625 * (1-36*eps) which is somewhere around 6.8E-10 seconds
current_tim=current_tim+datenum(0,0,0,1,0,0) ;%adding one hour in each loop
Remember that datenum(0,0,0,1,0,0) is going to be expressed in floating point as fractions of a day, not as integral hours. As 1/24 is not exactly representable in double precision floating point, the double precision representation of 1/24 is going to be either a hair less than the true 1/24 or a hair more than the true 1/24. When you start adding together those hairs, you are going to end up with values that are not exactly what they should be algebraically, leading to problems like you saw.
Try
start_tim=datenum(datestr('01-May-2014 00:00:00'));
for k=1:24*7
current_tim = start_tim + (k-1)/24; %k hours
datestr(current_tim)%checking
hour(current_tim)%checking
[out] = YourFunction(theta_pre,weaData,current_tim,I(k));
end
2 commentaires
Peter Perkins
le 20 Juin 2017
This is one reason why you should, if possible, use datetime, and not datenum. datetime does not suffer from this round-off problem, even after a much longer sequence.
>> d0 = datetime
d0 =
datetime
19-Jun-2017 23:21:37
>> d = d0 + cumsum(hours(ones(1,24*10000)));
>> d(end)
ans =
datetime
04-Nov-2044 23:21:37
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Dates and Time dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!