Ältere Kommentare anzeigen
Hi
Why this bucle doesnt end?
x=0;
while x~=10
x=x+0.1
end
2 Kommentare
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
Akzeptierte Antwort
Weitere Antworten (1)
Star Strider
am 21 Okt. 2017
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.
Kategorien
Mehr zu Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!