# How to deal with rounding error in this example?

4 views (last 30 days)
Kamia Kavi on 10 Dec 2022
Commented: Walter Roberson on 10 Dec 2022
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

Alan Stevens on 10 Dec 2022
i = 1:20001;
A = -2000 + (i-1)*0.2;
Walter Roberson on 10 Dec 2022
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

### Categories

Find more on Dates and Time in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!