![]() Var deltaUnit = Convert.ToDecimal(Math.Pow(0.1, decimals)) * Math.Sign(delta) Var rounded = original.Select(x => Math.Round(x, decimals)).ToList() ĭebug.Assert(Math.Round(forceSum, decimals) = forceSum) public static List GetPerfectRounding(List original, I wrote a C# version rounding helper, the algorithm is same as Varun Vohra's answer, hope it helps. The algorithm and code reflect that simplification. This answer originally advocated going through every possible combination of round up/round down, but as pointed out in the comments a simpler method works better. Even though 89.0 needs no rounding whatsoever, one of the values in that list needed to be rounded up the lowest relative error results from rounding up that large value rather than the much smaller alternatives. > round_to_100()Īs you can see with that last example, this algorithm is still capable of delivering non-intuitive results. from math import isclose, sqrtĭivisor = sqrt(1.0 if actual > round_to_100() Putting it all together in Python looks like this. The code I give below prefers to round up the values on the left. This is unavoidable, and the result will be completely arbitrary. You may still have more than one combination with the same error sum, for example 33.3333333, 33.3333333, 33.3333333.
0 Comments
Leave a Reply. |