How can I correct a rounding error??
8 次查看(过去 30 天)
显示 更早的评论
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??
0 个评论
回答(1 个)
James Tursa
2016-4-20
Welcome to the world of floating point arithmetic. See this post:
2 个评论
James Tursa
2016-4-20
编辑:James Tursa
2016-4-20
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!