while loop and for loop get different result

조회 수: 1 (최근 30일)
LIN kai
LIN kai 2018년 8월 2일
편집: Stephen23 2018년 8월 3일
This is a simple problem.I think I had coded correct.But it's still have some problem. The problem is why these three plot are different?

답변 (3개)

Masoud
Masoud 2018년 8월 2일
I saw no difference in figures, but your loops may be different because you wrote : "while t<40" which does not include the 40, it self. But "for" contains the upper bound, which is 40. In other word, your first loop is done 4000 times, however, the "for" loop runs 4001 times. This may be the main result of difference that you are looking for.

Bob Thompson
Bob Thompson 2018년 8월 2일
The while loop doesn't produce the same plot because the values of t are not exactly the same as the values desired. If you look at the final value of t in long format you get 40.000000000000611. Although this is effectively 40, when you subtract 40 from it you do not get 0, so the dirac() command does not result in 0.
Unfortunately, I do not know why the while loop produces this error, but it is the reason you aren't getting the same plot.
  댓글 수: 2
Stephen23
Stephen23 2018년 8월 2일
편집: Stephen23 2018년 8월 3일
"Unfortunately, I do not know why the while loop produces this error..."
Because of this line:
t=t+0.01;
The value 0.1 cannot be represented using binary floating point numbers, so that addition is actually
t = t+0.1+someError
This addition (with error) is repeated lots of times, thus introducing more and more error into the calculated values. In short, using a loop is a bad way to define those values. MATLAB offers much more numerically robust methods via linspace and the colon operators.
Learn about the practical limits of floating point numbers:
And some external links on this topic:
Bob Thompson
Bob Thompson 2018년 8월 2일
Huh, I suppose the binary makes sense. I had been able to track it down to that line as well, I just didn't have a good reason of why there was error.

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


LIN kai
LIN kai 2018년 8월 3일
Thanks for everyone's answer. I'm already understand.

카테고리

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