Simple counter won't trigger if statement

조회 수: 3 (최근 30일)
Tilman
Tilman 2013년 6월 28일
Hello, there is something strange happening when I run this code (workspace is empty before I run this)
tplot = 0;
for t = 1:100
tplot = tplot+0.1;
if tplot == 1
tplot
tplot = 0;
end
end
It never jumps inside the if block. When I increase tplot by 0.2 or 0.5 instead of 0.1 it works. I used the debugger to see what's happening when I use 0.1. When tplot reaches 1.0000 it totally ignores the if part.
Do you encounter the same problem? If so, what could be the reasen for this?

채택된 답변

Roger Stafford
Roger Stafford 2013년 6월 28일
This is a classic beginner's problem. Your computer uses binary floating point numbers, and as such cannot exactly represent the fraction 0.1. For that reason after you have multiplied the approximation to 0.1 by ten, the result won't be an exact 1. It will probably be off in the least bit or bits. You should allow room for a small deviation from an exact 1 in your 'if' statement.

추가 답변 (1개)

Tilman
Tilman 2013년 6월 29일
Thank you Roger. I use Matlab for 3 years now and never run into this problem.
  댓글 수: 1
Roger Stafford
Roger Stafford 2013년 6월 29일
You should get familiar with the double and single precision binary formats of floating point numbers. It would be well worth your time. It would allow you to have a better grasp of what to expect in rounding errors for various computations.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by