How to deal with rounding error in this example?

조회 수: 6 (최근 30일)
Kamia Kavi
Kamia Kavi 2022년 12월 10일
댓글: Walter Roberson 2022년 12월 10일
I want to add 0.2 to -2000 until I reach 2000. Apparently, some rounding errors happen in the code below. What is the solution to avoid that and the result will be exact, so -99.6?
A = (-2000: 0.2 : 2000)
A(9503)
>> -99.599999999999909

답변 (1개)

Alan Stevens
Alan Stevens 2022년 12월 10일
How about
i = 1:20001;
A = -2000 + (i-1)*0.2;
  댓글 수: 4
Walter Roberson
Walter Roberson 2022년 12월 10일
The only way to get the exact same bit representation is the literal -99.6 is to perform the operation in integers until the last moment -- though scaling the addend before doing addition and then scaling back gets close .
Remember, though, that 1/10th is simply not exactly representable in any finite-length binary floating point system. There is no integers N, M such that N / (2^M) is 1/10 exactly . In order for N / (2^M) == 1/10 exactly then (10*N)/(2^M) would have to equal 1, and you would have the task of finding an integer multiple of 10 that is an exact power of 2. Which is not going to happen since 10 = 2*5 so you would need to find an integer multiple of 5 that is an exact power of 2.
i = 1:20001;
A = -2000 + (i-1)*0.2;
A9503 = A(9503);
B9503 = -2000 + 9502*0.2
B9503 = -99.6000
C9503 = -2000 + 9502/5
C9503 = -99.6000
D9503 = (-2000*5 + 9502)/5
D9503 = -99.6000
E9503 = (-2000/.2 + 9502) * 0.2
E9503 = -99.6000
fprintf('A(9503) = %.999g\n', A9503);
A(9503) = -99.59999999999990905052982270717620849609375
fprintf('B(9503) = %.999g\n', B9503);
B(9503) = -99.59999999999990905052982270717620849609375
fprintf('C(9503) = %.999g\n', C9503);
C(9503) = -99.59999999999990905052982270717620849609375
fprintf('D(9503) = %.999g\n', D9503);
D(9503) = -99.599999999999994315658113919198513031005859375
fprintf('E(9503) = %.999g\n', E9503);
E(9503) = -99.6000000000000085265128291212022304534912109375
fprintf('-99.6 = %.999g\n', -99.6)
-99.6 = -99.599999999999994315658113919198513031005859375
differenceA = -99.6 - A9503
differenceA = -8.5265e-14
differenceB = -99.6 - B9503
differenceB = -8.5265e-14
differenceC = -99.6 - C9503
differenceC = -8.5265e-14
differenceD = -99.6 - D9503
differenceD = 0
differenceE = -99.6 - E9503
differenceE = 1.4211e-14
[differenceA, differenceB, differenceC, differenceD, differenceE] / eps(-99.6)
ans = 1×5
-6 -6 -6 0 1

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by