这是一个有效的浮动是比较占小数定数? [英] Is this a valid float comparison that accounts for a set number of decimal places?
问题描述
我正在写的扩展方法,使用小数点(显著数字)的一组数字,以确定它们是否相等,而不是一个公差或百分比差异来比较两个浮动。翻翻有关浮动比较,我看到复杂的实现的其他问题。 ?有我过于简单,或者这是有效的。
I'm writing an extension method to compare two floats using a set number of decimal points (significant figures) to determine if they are equal instead of a tolerance or percentage difference. Looking through the other questions regarding float comparison I see complex implementations. Have I oversimplified or is this valid?
/// <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);
}
注意:我在寻找一个比较在小数位,不宽容。我不想1000000等于1,000,001。
Note: I'm looking for a comparison on decimal places, not tolerance. I don't want 1,000,000 to equal 1,000,001.
推荐答案
根据@逸岸的答案,并在这两个问题的答案的一些意见我想出了
Based on @infact's answer and some comments in both the question and the answer I came up with
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);
}
这有接受任何整数benfit,你可以检查> 1.0精度通过采用精密= -x,其中x是10至核对电源。
This has the benfit of accepting any integer, you could check for > 1.0 precision by using precision = -x, where x is the power of 10 to check against.
我也建议使默认精度= 3,这将使你的精度下降一分钱的十分之一,在默认情况下,如果这种方法被用于金融。
I would also recommend making the default precision = 3, which would give you accuracy down to a tenth of a penny, by default, if this method were used for financials.
这篇关于这是一个有效的浮动是比较占小数定数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!