MATLAB: While loop ends too early

while loop

Hi everyone,
Why is this loop not executed for t_max = 5.0000e-04 anymore? if I output t, the maximum (last) value is 5.0000e-04 instead of 5.0100e-04
delta_t = 10e-7;
t_max = 5.0000e-04; %[s]
t = 0;
while t <= t_max
t = t+delta_t;
end

Best Answer

Image Analyst and Sriram explained the reason as it is caused by the finite precision of floating-point representation. One way is to solve the issue with limited precision is to use variable precision arithmetic
delta_t = vpa(10e-7);
t_max = vpa(5.0000e-04); %[s]

t = vpa(0);
while t <= t_max
t = t+delta_t;
end
However, note that this will be slower as compared to the numeric version. The other solution is to add a tolerance value for comparison
delta_t = 10e-7;
t_max = 5.0000e-04; %[s]
t = 0;
while t <= t_max + 1e-10 % small tolerance in comparison
t = t+delta_t;
end