Bucle doesn't end
显示 更早的评论
Hi
Why this bucle doesnt end?
x=0;
while x~=10
x=x+0.1
end
2 个评论
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
采纳的回答
更多回答(1 个)
Star Strider
2017-10-21
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!