Decimal order of addition affects results

主宰稳场 提交于 2019-12-05 11:45:34

The entire field of Numerical analysis is devoted to studying these kind of effects and how to avoid them.

To produce the best result when summing a list of floating point numbers, first sort the list from smallest to largest, and add them up in that order.

You might suspect a decimal type to be immune to the bane of double-users everywhere.

But because decimal has 28-29 digits of precision and your input is asking for the sum of 29 digits of precision of data, you're right at the very edge of what your data type can accurately represent.

According to MSDN, the precision of a decimal is 28-29 digits. At least one of your numbers is 29 digits, so you are likely exceeding the limit.

Because of rounding the result of sum for multiple numbers may vary depending upon the order in which they are summed. This won't happen in mathematics but the way sum is computed in your example the order matters. result += number; sums and stores the result in result variable. At that time some of the precision is lost. However, if we do it in the same order, it would always result in same result.

Console.WriteLine(numbers.Sum()); // Always returns 9.214085249270111332166335344

Because of this many programs use Bankers rounding which produces closer results. Please know the precision is always lost. There is no way to store "accurate" floating point number in compuiter memor

Rounding

Bankers Rounding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!