如何正确生成具有 5 分钟时间戳的文件名?
How can I generate filenames with 5 minute timestamps correctly?
我使用下面的代码根据时间步数每五分钟生成一次文件名。但它不能正常工作。如果你打开 precipFileNames,你会看到中途,代码每 5 分钟停止一次,而是 5 分钟 1 秒,生成如下文件名:
E:\MRMS04\PRECIPRATE.20040402.051959.tif
我怎样才能正确地做到这一点?
timeSteps = 417;
pathstr = 'E:\MRMS04';
startTime = 7.320395312500000e+05;
peakTime2 = 7.320400104166666e+05;
precipFileNames=cell(timeSteps,1);
for l = 1:timeSteps
%precipFileNames{m} = strcat(fileparts(refFile), filesep, datestr(startTime, 'yyyy'), filesep,'PRECIPRATE.',datestr(startTime, 'yyyymmdd.hhMMss'), '.tif');
precipFileNames{l} = strcat(pathstr(1:end-4), datestr(startTime, 'yyyy'), filesep, 'PRECIPRATE.',datestr(peakTime2, 'yyyymmdd.hhMMss'), '.tif');
peakTime2 = addtodate(peakTime2, -5, 'minute'); %No. of times we go back in time from peak time
end
Date/times 内部使用浮点数存储。每次通过循环,您都会将一个非常小的值(5 分钟,0.0035
)添加到一个相对较大的值(7e05
-ish),这会导致累积 floating point arithmetic errors。这些错误表现为与您的预期值略有不同。
因为你在一个循环中一遍又一遍地执行这个加法(到 peakTime2
),一次迭代的浮点误差被放大,因为下一次迭代取决于前一次的结果。
而不是不断更新 peakTime2
我会更改 delta 值并将其应用于 original datetime 对象每次通过循环。这样就没有错误的积累,你只需要执行一次减法就可以得到一个特定的值。
for k = 1:timeSteps
% Compute how many minutes to shift this iteration
shift = -5 * (k - 1);
% Apply the shift to the reference time
thistime = addtodate(peakTime2, shift, 'minute');
% Create the filename
precipFileNames{k} = strcat(pathstr(1:end-4), ...
datestr(startTime, 'yyyy'), ...
filesep, ...
'PRECIPRATE.', ...
datestr(thistime, 'yyyymmdd.hhMMss'), ...
'.tif');
end
作为旁注,为了人们阅读您的代码,我强烈建议不要使用 l
作为变量,因为它看起来很像 1
.
我使用下面的代码根据时间步数每五分钟生成一次文件名。但它不能正常工作。如果你打开 precipFileNames,你会看到中途,代码每 5 分钟停止一次,而是 5 分钟 1 秒,生成如下文件名:
E:\MRMS04\PRECIPRATE.20040402.051959.tif
我怎样才能正确地做到这一点?
timeSteps = 417;
pathstr = 'E:\MRMS04';
startTime = 7.320395312500000e+05;
peakTime2 = 7.320400104166666e+05;
precipFileNames=cell(timeSteps,1);
for l = 1:timeSteps
%precipFileNames{m} = strcat(fileparts(refFile), filesep, datestr(startTime, 'yyyy'), filesep,'PRECIPRATE.',datestr(startTime, 'yyyymmdd.hhMMss'), '.tif');
precipFileNames{l} = strcat(pathstr(1:end-4), datestr(startTime, 'yyyy'), filesep, 'PRECIPRATE.',datestr(peakTime2, 'yyyymmdd.hhMMss'), '.tif');
peakTime2 = addtodate(peakTime2, -5, 'minute'); %No. of times we go back in time from peak time
end
Date/times 内部使用浮点数存储。每次通过循环,您都会将一个非常小的值(5 分钟,0.0035
)添加到一个相对较大的值(7e05
-ish),这会导致累积 floating point arithmetic errors。这些错误表现为与您的预期值略有不同。
因为你在一个循环中一遍又一遍地执行这个加法(到 peakTime2
),一次迭代的浮点误差被放大,因为下一次迭代取决于前一次的结果。
而不是不断更新 peakTime2
我会更改 delta 值并将其应用于 original datetime 对象每次通过循环。这样就没有错误的积累,你只需要执行一次减法就可以得到一个特定的值。
for k = 1:timeSteps
% Compute how many minutes to shift this iteration
shift = -5 * (k - 1);
% Apply the shift to the reference time
thistime = addtodate(peakTime2, shift, 'minute');
% Create the filename
precipFileNames{k} = strcat(pathstr(1:end-4), ...
datestr(startTime, 'yyyy'), ...
filesep, ...
'PRECIPRATE.', ...
datestr(thistime, 'yyyymmdd.hhMMss'), ...
'.tif');
end
作为旁注,为了人们阅读您的代码,我强烈建议不要使用 l
作为变量,因为它看起来很像 1
.