How can I correct a rounding error??

12 views (last 30 days)
Jake
Jake on 20 Apr 2016
Edited: James Tursa on 20 Apr 2016
Hi MATLAB experts,
I have a quick question.. I am trying to find absolute value of sum weights as an example below:
weight = [0.05; 0.05; -0.05; -0.05];
sum_weight = abs(nansum(weight,1));
This sum of weights should turn out '0'. However, MATLAB calculates wrong, resulting in a very small number close to '0' something like this 1.38777878078145E-17.
Can you please tell me what should be adjusted in this??

Answers (1)

James Tursa
James Tursa on 20 Apr 2016
Welcome to the world of floating point arithmetic. See this post:
  2 Comments
Jake
Jake on 20 Apr 2016
Hi James, Thanks for your comment. However, since I am still new to MATLAB, I don't get the point well from the link. Can you please more elaborate on that if you don't mind??
Thanks!
James Tursa
James Tursa on 20 Apr 2016
Edited: James Tursa on 20 Apr 2016
Well, for your particular example, using R2015a 32-bit Win7 I get the following:
>> weight = [0.05; 0.05; -0.05; -0.05];
>> sum_weight = abs(nansum(weight,1))
sum_weight =
0
So I can't reproduce your small number. But in general, one should not necessarily expect floating point calculations to get "exact" answers that seem obvious in decimal notation. E.g., 0.05 can't be represented in IEEE floating point double precision exactly. Using the num2string utility from the FEX yields the following:
>> num2strexact(0.05)
ans =
5.000000000000000277555756156289135105907917022705078125e-2
So when you start doing calculations with such approximations, results that look like easy exact answers in the decimal base are not necessarily going to turn out that way in IEEE double (or single). If you need this to be the case in your code, then you need to account for this behavior. E.g., use tolerances when comparing numbers, etc.

Sign in to comment.

Tags

Products

Community Treasure Hunt

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

Start Hunting!