Hi
Why this bucle doesnt end?
x=0;
while x~=10
x=x+0.1
end

댓글 수: 2

Stephen23
Stephen23 2017년 10월 21일
편집: Stephen23 2017년 10월 21일
Note: "bucle" is Spanish for loop.
Stephen23
Stephen23 2017년 10월 21일
편집: Stephen23 2017년 10월 21일
The reason is basically because all numbers in your computer are stored as finite binary numbers, and they cannot represent exactly those decimal fractions (in just the same way that you cannot write 1/3 exactly using a finite decimal fraction).
Your code tests for equivalence of floating point values, which is a very buggy and unreliable way to write code. You need to change your algorithm to take into account floating point error:
etc, etc, etc.
This is worth reading as well:
PS: the solution, as every of those links will tell you, is never compare for equality between floating point values, and always use a tolerance:
abs(a-b)<tol

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

 채택된 답변

the cyclist
the cyclist 2017년 10월 21일
편집: the cyclist 2017년 10월 21일

1 개 추천

Because the number 0.1 cannot be represented exactly in typical floating point systems. It will be off in approximately the 16th decimal place, and so will not be exactly 10 after 100 times through this loop.
You need to include a tolerance, if you want to check equality of floating point numbers.
You can read more details if you search for these keywords, but here is one good place.

추가 답변 (1개)

Star Strider
Star Strider 2017년 10월 21일

1 개 추천

It is called ‘floating-point approximation error’, and is analogous to representing the fraction ‘1/3’ in decimal notation, producing 0.33333....
Running your code (after adding an if block to stop it when x>10.2) results in:
x =
9.89999999999998
x =
9.99999999999998
x =
10.1
so ‘x’ never actually equals 10.
See: Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? (link) for a full explanation.

카테고리

도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기

태그

질문:

2017년 10월 21일

편집:

2017년 10월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by