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

2 Kommentare

Stephen23
Stephen23 am 21 Okt. 2017
Bearbeitet: Stephen23 am 21 Okt. 2017
Note: "bucle" is Spanish for loop.
Stephen23
Stephen23 am 21 Okt. 2017
Bearbeitet: Stephen23 am 21 Okt. 2017
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

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

the cyclist
the cyclist am 21 Okt. 2017
Bearbeitet: the cyclist am 21 Okt. 2017

1 Stimme

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.

Weitere Antworten (1)

Star Strider
Star Strider am 21 Okt. 2017

1 Stimme

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.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by