C#四舍五入MidpointRounding.ToEven与MidpointRounding.AwayFromZero的区别

23
在C#中,使用MidpointRounding.ToEvenMidpointRounding.AwayFromZero这两种小数舍入策略是否存在精度上的区别?我的意思是,这两种舍入策略是否都可以确保被舍入的数字之间均匀分布,或者其中一种舍入策略相比另一种舍入策略过于偏向某些被舍入的数字?

1
这个问题的被接受答案:https://dev59.com/GHVC5IYBdhLWcg3wYQEp 应该能够解决你的疑惑 :) - MattDavey
我认为下面的例子更能说明问题。 :) - Carlo V. Dango
1
是的,它确实有 :) - 链接的问题有很多背景信息.. - MattDavey
3个回答

52

来自.NET文档页面上的Math.Round:

https://learn.microsoft.com/en-us/dotnet/api/system.math.round#midpoint-values-and-rounding-conventions

默认情况下,Math.Round使用MidpointRounding.ToEven。 大多数人不熟悉“四舍六入五成双”,而更常见的替代方法是“四舍五入”,这在学校中更常被教授。 .NET默认使用“四舍六入五成双”,因为它在统计学上更优秀,不像“四舍五入”那样具有向上舍入的倾向(假设要舍入的数字倾向于为正数),导致向上舍入的次数略微多于向下舍入。

根据数据集的不同,对称算术舍入可能会引入重大偏差,因为它总是将中间值上调。举个简单的例子,假设我们想确定三个值1.5、2.5和3.5的平均值,但在计算平均值之前,我们要先将它们四舍五入到最接近的整数。请注意,这些值的真实平均值是2.5。使用对称算术舍入,这些值变为2、3和4,它们的平均数是3。使用银行家舍入,这些值变为2、2和4,它们的平均数是2.67. 因为后一种舍入方法更接近三个值的真实平均值,所以它提供了最小的数据损失。


14

如果您的值为123.45,则

123.5 <-- 远离零的中间舍入方式(MidpointRounding.AwayFromZero)
123.4 <-- 最近偶数的中间舍入方式(MidpointRounding.ToEven)


0
1) .NET using MidpointRounding.ToEven for default method of Math.Round
2) MidpointRounding.ToEven will round off to upper limit if fraction value grater then 5
3) MidpointRounding.AwayFromZero will round off to upper limit if fraction value equal and grater then 5
4) for e.g. if we want to Round off 12.1250 in 2 digit with 2 fraction
Math.Round(12.1250,2,MidpointRounding.ToEven) => 12.12 (fraction value in 50)
Math.Round(12.1250,2,MidpointRounding.AwayFromZero) => 12.13

Math.Round(12.1251,2,MidpointRounding.ToEven) => 12.13 (fraction value in 51)
Math.Round(12.1251,2,MidpointRounding.AwayFromZero) => 12.13

你的回答可以通过提供更多的支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接