Filter löschen
Filter löschen

gets slightly off value when summing

1 Ansicht (letzte 30 Tage)
Sharon Timotius
Sharon Timotius am 1 Nov. 2022
Kommentiert: John D'Errico am 4 Nov. 2022
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.

Akzeptierte Antwort

Eric Delgado
Eric Delgado am 1 Nov. 2022
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 Kommentare
Eric Delgado
Eric Delgado am 4 Nov. 2022
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
John D'Errico
John D'Errico am 4 Nov. 2022
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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by