MATLAB Answers

Unexpected result from linspace function

조회 수: 47(최근 30일)
Why the result of this code
B1 = 0:0.1:1.8;
B2 = linspace(0,1.8,19)
is 5.5511e-17? I found a workaround, which is
B1 = 0:01:18;
B1 = B1/10;
But I am still wondering why the first code does not produce what it should?

  댓글 수: 0

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

채택된 답변

Rik 15 Aug 2018
Welcome to the wondrous world of floating point numbers. Matlab is a computer program, so it works with binary. Some values are impossible to represent in a binary expansion, so they get rounded. This can be different for each algorithm, so even if the end result can be represented, rounding errors can build up. That is the use case for the eps function: it shows you what the magnitude is of possible errors.
As a decimal example, consider this: (1/3)*3. Assuming I can only store 2 decimal digits, that would be 0.33*3=0.99, even if the correct answer doesn't need 2 decimals.

  댓글 수: 5

표시 이전 댓글 수: 2
Rik 15 Aug 2018
It isn't a problem with the minus function either, as array(4)==0.3 returns false. That is the reason why you shouldn't use equality in such cases, but abs(array(4)-0.3)<eps (or use functions that do this internally, like ismembertol and uniquetol).
Stephen Cobeldick
Stephen Cobeldick 15 Aug 2018
"But this issue can be overcomed by using another algorithm inside 0:0.1:1.8 notation. Why this has not been already implemented? It seems to be obvious. Just like this:"
No, that does not overcome the "issue" at all. The first thing is to understand that 0.1 cannot be stored exactly by binary floating point numbers, in exactly the same way that you cannot write 1/3 as a finite decimal. Also understand that different calculations can produce different floating point error.
Your "algorithm" does not solve anything, because the floating point error will always be there. And no matter what way you calculate those values, someone will compare those values with the results of a different calculation that results in a different floating point error and so the comparison will fail in exactly the same way. You have not solved anything.
The actual solution is to compare the absolute value against a tolerance:
In any case, this has all been discussed in lots of detail before. Start by reading these:
This is worth reading as well:
Rostislav Teryaev
Rostislav Teryaev 15 Aug 2018
Thank you!

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

추가 답변(0개)




Community Treasure Hunt

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

Start Hunting!

Translated by