How to deal with rounding error in this example?
24 ビュー (過去 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 で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!