MATLAB Answers

0

Why is matlab giving me a a very small number when the answer should be EXACTLY zero?

Asked by Amer Bin Eshaq on 15 Oct 2019
Latest activity Answered by Walter Roberson
on 15 Oct 2019
m=[-1*1.8 1.2 0.6]*[1,1,1]'
the answer
m = -2.2204e-16
What shall I do to make it zero?

Tags

3 Answers

Answer by Rik
on 15 Oct 2019
Edited by Rik
on 15 Oct 2019

Because not all numbers can be stored as an exact binary number, some calculations will have rounding errors.
%exagerated example:
>> a=1/3
a=0.333
>> b=3*a
b=0.999
See this doc page for more information.
In many cases it is smarter to compare the abs(diff()) of two numbers, instead of testing equality. Functions like ismembertol can also be very helpful.

  0 Comments

Sign in to comment.


Answer by Shubham Gupta on 15 Oct 2019

It must be something to do with the limitation of matrix multiplication and the computing error comes with the this type of multiplication. You can use round() to round off the really small numbers. For e.g.
m=round([-1*1.8 1.2 0.6]*[1,1,1]',8); % this will give 0 if matrix multiplication is less than 1e-8
Using this, round(num,8) will round off the number smaller than 10^-8 to 0.
Of course, you can increase the number (i.e. 8) to get the desired level of accuracy.

  0 Comments

Sign in to comment.


Answer by Walter Roberson
on 15 Oct 2019

m=[-1*1.8 1.2 0.6]*[1,1,1]'
In scientific computing, the meaning of that is
m=[ range(-18/10-5/100,-18/10+5/100,'semiopen'), range(12/10-5/100,12+5/100,'semiopen') range(6/10-5/100,6/10+5/100,'semiopen')]*[exactly(1),exactly(1),exactly(1)]'
where range(A,B,'semiopen') is the semi-open interval [A,B) .
That is, every floating point number you write expresses the set of numbers that round to the rational equivalent of the floating point number entered. You are not asking to calculate an exact value: you are asking to make the calculation over sets of values, and the "right" answer is everything in the resulting set. The result should not be EXACTLY zero.
If you write,
syms d1 d2 d3
assume(-5/100 <= d1 & d1 < 5/100)
assume(-5/100 <= d2 & d2 < 5/100)
assume(-5/100 <= d3 & d3 < 5/100)
m =[-1*18/10+d1, 12/10+d2, 6/10+d3]*[1,1,1]'
then you will get the mathematical result, which is d1+d2+d3 -- mathematically the solution is the sum of the uncertainties in expressing the numbers. The uncertainty for each is a range, though. Every result between -15/100 inclusive and 15/100 exclusive is possible for m.

  0 Comments

Sign in to comment.