How can I correct a rounding error??

13 ビュー (過去 30 日間)
Jake
Jake 2016 年 4 月 20 日
編集済み: James Tursa 2016 年 4 月 20 日
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??

回答 (1 件)

James Tursa
James Tursa 2016 年 4 月 20 日
Welcome to the world of floating point arithmetic. See this post:
  2 件のコメント
Jake
Jake 2016 年 4 月 20 日
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 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 ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by