Borrar filtros
Borrar filtros

Why 'hour' function output and 'datestr' output is not matching?

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Walter Roberson
Walter Roberson el 15 de Jun. de 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 comentarios
Jannatun Nahar
Jannatun Nahar el 15 de Jun. de 2017
Thanks! It works great.
Peter Perkins
Peter Perkins el 20 de Jun. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by