How to deal with rounding error in this example?
8 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Alan Stevens
2022-12-10
How about
i = 1:20001;
A = -2000 + (i-1)*0.2;
4 个评论
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
C9503 = -2000 + 9502/5
D9503 = (-2000*5 + 9502)/5
E9503 = (-2000/.2 + 9502) * 0.2
fprintf('A(9503) = %.999g\n', A9503);
fprintf('B(9503) = %.999g\n', B9503);
fprintf('C(9503) = %.999g\n', C9503);
fprintf('D(9503) = %.999g\n', D9503);
fprintf('E(9503) = %.999g\n', E9503);
fprintf('-99.6 = %.999g\n', -99.6)
differenceA = -99.6 - A9503
differenceB = -99.6 - B9503
differenceC = -99.6 - C9503
differenceD = -99.6 - D9503
differenceE = -99.6 - E9503
[differenceA, differenceB, differenceC, differenceD, differenceE] / eps(-99.6)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!