How to deal with Matlab's inprecision?

1 次查看(过去 30 天)
Kailin
Kailin 2019-12-3
评论: Rik 2019-12-3
Dear all,
I have a 15*11 matrix denoted by s. Each row is the same. I looks like this:
Image 52.png
(I verified that after I run the following code "bb=s-[repmat(s(1,:),nbk,1) ]", I get sum(sum(bb))=0.)
Therefore, it is natural that:
(1) s(1,9)/sum(s(1,9))-s(1,8)/sum(s(1,8))=0
(2) s(1,9)/sum(s(1:2,9))-s(1,8)/sum(s(1:2,8))=0
However,
(3) s(1,9)/sum(s(1:3,9))-s(1,8)/sum(s(1:3,8)) which is supposed to be 0, but I get: ans = -5.5511e-17
This minor difference affects my other calculation as I need to compare the differences between two elements. When the differences are supposed to be zero, matlab gives me an inprecise number.
I wondered first why that happend in (3), but not (1) and (2), and how I can tackle it. I attached the matrix for s below.
Thanks,
K

回答(1 个)

Walter Roberson
Walter Roberson 2019-12-3
You cannot fix that problem as long as you are using binary floating point numbers. Look at this:
>> 1 + 1e-17 - 1
ans =
0
Algebraically you would expect 1e-17, but you get 0 instead. http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F This is a problem inherent in binary floating point representation and using larger floating point words (e.g., some languages support quad precision as well as double precision) merely postpones the problem rather than eliminating it.
In fact, it is a problem not just with binary floating point, but also with decimal floating point, and also with floating point with any fixed base, and even with floating point that works with a finite mixed of primes somehow (e.g., base 60). You get equivalent problems with fixed point calculation in any finite list of bases as well.
The only time you do not get the problem is when you calculate using infinite precision... which can require infinite time and infinite memory... and our mathematics has not advanced enough to be able to tell whether is rational or irrational, so don't go expecting too much even if you have infinite time and memory available to you.
  1 个评论
Rik
Rik 2019-12-3
And the solution is to compare to a tolerance (e.g. 2*eps). You can write that yourself or use functions like ismembertol and uniquetol.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by