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