How can I correct a rounding error??
조회 수: 11 (최근 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!