Decimal rounding errors upon division (C#)

∥☆過路亽.° 提交于 2019-12-10 14:04:34

问题


I have basically four numbers (say 100, 200, 300, 400), and I need to calculate the probability as 100/(100+200+300+400), 200/(100+200+300+400), and so on.

When I use the decimal data type to store these probabilities, they don't up to one due to round issues. What's the best way to past this without making the probabilities too inaccurate? Basically I do this calculation many many times, so I don't want to have to change all the divisions into Math.Round stuff. :|


回答1:


The solution is straightforward: if it hurts when you do that then don't do that.

If you have rational probabilities, that is, probabilities that are ratios of whole numbers, and you want them to add to exactly one, then don't convert them to decimal or double in the first place. Use an arbitrary-precision rational type to represent your arbitrary precision rationals.

There's an arbitrary-precision rational type included with Microsoft Solver Foundation; you could download and use that. Or, it is easy to write your own by simply making an immutable struct that has two BigIntegers for the numerator and denominator, and then write implementations of the operators you need.




回答2:


There is no call to Math.Round that will resolve this the way you want. The issue is that all of the roundings must work together - ie. have awareness that individually they are all right but viewed together they are wrong.

One way to deal with rounding error of division, is to adjust the values to accomodate it:

List<decimal> decimals = new List<decimal>() { 100m, 200m, 300m, 300m };
decimal total = decimals.Sum();

List<decimal> probabilities = decimals.Select(x => x / total).ToList();
decimal sum = probabilities.Sum();
decimal error = 1.0m - sum;
Console.WriteLine("{0}, {1}", sum, error);

probabilities[0] += error; //put all of the error into the first item.
decimal newSum = probabilities.Sum();

Console.WriteLine(newSum);

More sophisticated approaches spread the error over the values. For example, spreading 0.0000000000000000000000000004 over 4 values instead of 1.



来源:https://stackoverflow.com/questions/5910588/decimal-rounding-errors-upon-division-c

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