I found this problem
>> p1
p1 =
0.0050
>> p2
p2 =
0.0450
>> p1+p2 - 0.05
ans =
-6.9389e-18
Obviously p1 + p2 is 0.05 but I think due to loss of data when summed the result is not exactly equal to 0.05. Is there a way to fix this (as in, how do i restore p1+p2 to 0.05)? the code above is not what I am using, it's only for reference. Thanks in advance.

 채택된 답변

Eric Delgado
Eric Delgado 2022년 11월 1일

1 개 추천

It's float operation universe. :)
p1 = 0.005;
p2 = 0.0450;
% Instead of:
p1+p2 == 0.05
ans = logical
0
% Try this:
abs(p1+p2-0.05) <= 1e-5 % You could use 1e-17 and still will receive a true logical value
ans = logical
1

댓글 수: 3

Sharon Timotius
Sharon Timotius 2022년 11월 1일
편집: Sharon Timotius 2022년 11월 1일
My goal is to restore the p1+p2 to 0.05. Is there a way? thanks
Nop... but you can use round to force it.
p1 = 0.005;
p2 = 0.045;
p1+p2 == 0.05
ans = logical
0
round(p1+p2, 2) == 0.05
ans = logical
1
That could in general be dangerous, that is, using round to try to FORCE it to sum correctly. This is because even the number 0.05 is not exactly 0.05. 0.05 is NOT representable using floating point arithmetic, because the number is stored in a binary form using 52 binary bits.
In binary, the number 0.05 would be represented as the infinitely repeating bit sequence
0.0000110011001100110011001100110011001100110011001100110011...
where the ones represent negative powers of 2.
format long g
x = sum(2.^[-5 -6 -9 -10 -13 -14 -17 -18 -21 -22 -25 -26 -29 -30 -33 -34 -37 -38 -41 -42 -45 -46 -49 -50 -53 -54 -56])
x =
0.05
More accurately
sprintf('%0.55f',x)
ans = '0.0500000000000000027755575615628913510590791702270507812'
So while it LOOKS like 0.05, it is not, for the same reason that 1/3 is not finitely representable as a decimal. We can even do this test:
x == 0.05
ans = logical
1
And MATLAB even THINKS that number is the same as 0.05. But we know it is not.
So rounding such a result could conceivably produce something other than 0.05. Do I need to come up with a counter-example?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2022년 11월 1일

댓글:

2022년 11월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by