Kim*_*Kim 9 c# floating-point floating-point-precision
我正在编写一个扩展方法,使用一组小数点(有效数字)来比较两个浮点数,以确定它们是否相等而不是容差或百分比差异.通过关于浮点数比较的其他问题,我看到了复杂的实现.我是否过度简化或是否有效?
/// <summary>
/// Determines if the float value is equal to (==) the float parameter according to the defined precision.
/// </summary>
/// <param name="float1">The float1.</param>
/// <param name="float2">The float2.</param>
/// <param name="precision">The precision. The number of digits after the decimal that will be considered when comparing.</param>
/// <returns></returns>
public static bool AlmostEquals(this float float1, float float2, int precision = 2)
{
return (Math.Round(float1 - float2, precision) == 0);
}
Run Code Online (Sandbox Code Playgroud)
注意:我正在寻找小数位的比较,而不是容差.我不希望1,000,000等于1,000,001.
基于@infact的回答以及我提出的问题和答案中的一些评论
public static bool AlmostEquals(this float float1, float float2, int precision = 2)
{
float epsilon = Math.Pow(10.0, -precision)
return (Math.Abs(float1-float2) <= epsilon);
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以接受任何整数,您可以使用 precision = -x 检查 > 1.0 的精度,其中 x 是要检查的 10 的幂。
我还建议将默认精度设置为 3,如果将此方法用于财务分析,默认情况下,这将使您的准确度降至十分之一美分。