while loop ends too early

조회 수: 2 (최근 30일)
Ann Gerber
Ann Gerber 2020년 3월 21일
댓글: Ann Gerber 2020년 3월 22일
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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 3월 21일
편집: Ameer Hamza 2020년 3월 21일
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
  댓글 수: 1
Ann Gerber
Ann Gerber 2020년 3월 22일
Thank you so much!
I expected this would be the problem but didn't know how to solve it the good way.
Cheers :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Image Analyst
Image Analyst 2020년 3월 21일
Take the semicolon off and format long and you'll see why
format long g;
format compact
delta_t = 10e-7;
t_max = 5.0000e-04; %[s]
t = 0;
while t <= t_max
t = t+delta_t
end
t =
0.000498000000000006
t =
0.000499000000000006
t =
0.000500000000000006
You see, it ends up being slightly larger than 0.0005 so it doesn't even enter the loop that last time.
So, basically you need to see the FAQ for an explanation of digitization error: FAQ Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero?

Sriram Tadavarty
Sriram Tadavarty 2020년 3월 21일
Hi Ann,
The loop runs as expected, since the floating values are represented in IEEE 754 format as described here.
To know what the value of t that end from the loop, use format long as below:
format long
>> t_max
t_max =
5.000000000000000e-04
>> t
t =
5.000000000000056e-04
Observe that t is lager than t_max and thus, the loop ended.
Hope this helps.
Regards,
Sriram

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by