필터 지우기
필터 지우기

How can I correct a rounding error??

조회 수: 4 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by