Double.Equals 方法

定义

返回一个值,该值指示 Double 的两个实例是否表示同一个值。Returns a value indicating whether two instances of Double represent the same value.

重载

Equals(Double)

返回一个值,该值指示此实例和指定的 Double 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Double object represent the same value.

Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

Equals(Double)

返回一个值,该值指示此实例和指定的 Double 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Double object represent the same value.

public:
 virtual bool Equals(double obj);
public bool Equals (double obj);
override this.Equals : double -> bool
Public Function Equals (obj As Double) As Boolean

参数

obj
Double

要与此示例比较的 Double 对象。A Double object to compare to this instance.

返回

如果 true 与此实例相等,则为 obj;否则为 falsetrue if obj is equal to this instance; otherwise, false.

实现

注解

此方法实现 @no__t 的接口,并且执行的效果略优于 Equals,因为无需将 obj 参数转换为对象。This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.

扩大转换Widening Conversions

根据您的编程语言,可能会将 Equals 方法编码,其中参数类型的位数(比实例类型小)。Depending on your programming language, it might be possible to code a Equals method where the parameter type has fewer bits (is narrower) than the instance type. 这是可能的,因为某些编程语言会执行将参数表示为类型的隐式扩大转换,该类型的位数与实例的位数一样多。This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance.

例如,假设实例类型为 Double,并且参数类型 @no__t 为-1。For example, suppose the instance type is Double and the parameter type is Int32. Microsoft C#编译器将生成说明,以将参数的值表示为 @no__t 1 对象,然后生成一个 Double.Equals(Double) 方法,该方法将实例的值与参数的扩展表示形式进行比较。The Microsoft C# compiler generates instructions to represent the value of the parameter as a Double object, then generates a Double.Equals(Double) method that compares the values of the instance and the widened representation of the parameter.

请查阅编程语言的文档,以确定其编译器是否执行数值类型的隐式扩大转换。Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. 有关详细信息,请参阅类型转换表主题。For more information, see the Type Conversion Tables topic.

比较中的精度Precision in Comparisons

应慎用 @no__t 0 方法,因为两个值的精度不同,因此两个明显等效的值可能不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. 下面的示例报告 @no__t 值333333和除以3时返回的 Double 值不相等。The following example reports that the Double value .333333 and the Double value returned by dividing 1 by 3 are unequal.

// Initialize two doubles with apparently identical values
double double1 = .33333;
double double2 = 1/3;
// Compare them for equality
Console.WriteLine(double1.Equals(double2));    // displays false
' Initialize two doubles with apparently identical values
Dim double1 As Double = .33333
Dim double2 As Double = 1/3
' Compare them for equality
Console.WriteLine(double1.Equals(double2))    ' displays False

其中一种方法是定义两个值(例如,其中一个值的 .001%)之间的差异的可接受相对边距,而不是比较是否相等。Rather than comparing for equality, one technique involves defining an acceptable relative margin of difference between two values (such as .001% of one of the values). 如果这两个值之差的绝对值小于或等于该边距,则差异可能是由于精度的不同而导致的,因此,这些值可能是相等的。If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. 下面的示例使用此方法来比较. 33333 和1/3,前面的代码示例发现的两 @no__t 0 值为不相等。The following example uses this technique to compare .33333 and 1/3, the two Double values that the previous code example found to be unequal. 在这种情况下,值相等。In this case, the values are equal.

// Initialize two doubles with apparently identical values
double double1 = .333333;
double double2 = (double) 1/3;
// Define the tolerance for variation in their values
double difference = Math.Abs(double1 * .00001);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(double1 - double2) <= difference)
   Console.WriteLine("double1 and double2 are equal.");
else
   Console.WriteLine("double1 and double2 are unequal.");
' Initialize two doubles with apparently identical values
Dim double1 As Double = .33333
Dim double2 As Double = 1/3
' Define the tolerance for variation in their values
Dim difference As Double = Math.Abs(double1 * .00001)

' Compare the values
' The output to the console indicates that the two values are equal
If Math.Abs(double1 - double2) <= difference Then
   Console.WriteLine("double1 and double2 are equal.")
Else
   Console.WriteLine("double1 and double2 are unequal.")
End If

备注

由于 Epsilon 定义其范围接近零的正值的最小表达式,因此两个相似值之间的差值幅度必须大于 EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference between two similar values must be greater than Epsilon. 通常情况下,它的数量大于 EpsilonTypically, it is many times greater than Epsilon. 因此,建议不要在比较 Double 值是否相等时使用 EpsilonBecause of this, we recommend that you do not use Epsilon when comparing Double values for equality.

第二种方法涉及将两个浮点数之间的差与某个绝对值进行比较。A second technique involves comparing the difference between two floating-point numbers with some absolute value. 如果差异小于或等于该绝对值,则数字相等。If the difference is less than or equal to that absolute value, the numbers are equal. 如果大于,则数字不相等。If it is greater, the numbers are not equal. 一种替代方法是任意选择一个绝对值。One alternative is to arbitrarily select an absolute value. 但是,这是有问题的,因为可接受的差异幅度取决于 @no__t 值的大小。This is problematic, however, because an acceptable margin of difference depends on the magnitude of the Double values. 另一种替代方法是使用浮点格式的设计功能:两个浮点值的整数表示形式之间的差异指示了可以分隔它们的浮点值的数量。A second alternative takes advantage of a design feature of the floating-point format: The difference between the integer representation of two floating-point values indicates the number of possible floating-point values that separates them. 例如,0.0 和 Epsilon 之间的差值为1,因为当使用的 @no__t 值为零时,Epsilon 是可表示的最小值。For example, the difference between 0.0 and Epsilon is 1, because Epsilon is the smallest representable value when working with a Double whose value is zero. 下面的示例使用此方法来比较. 33333 和1/3,这是前面的代码示例中的两个 @no__t 0 值,它们的 @no__t 的方法不相等。The following example uses this technique to compare .33333 and 1/3, which are the two Double values that the previous code example with the Equals(Double) method found to be unequal. 请注意,该示例使用 BitConverter.DoubleToInt64Bits 方法将双精度浮点值转换为其整数表示形式。Note that the example uses the BitConverter.DoubleToInt64Bits method to convert a double-precision floating-point value to its integer representation.

using System;

public class Example
{
   public static void Main()
   {
      double value1 = .1 * 10;
      double value2 = 0;
      for (int ctr = 0; ctr < 10; ctr++)
         value2 += .1;
         
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1));
   }

   public static bool HasMinimalDifference(double value1, double value2, int units)
   {
      long lValue1 = BitConverter.DoubleToInt64Bits(value1);
      long lValue2 = BitConverter.DoubleToInt64Bits(value2);
      
      // If the signs are different, return false except for +0 and -0.
      if ((lValue1 >> 63) != (lValue2 >> 63))
      {
         if (value1 == value2)
            return true;
          
         return false;
      }

      long diff = Math.Abs(lValue1 - lValue2);

      if (diff <= (long) units)
         return true;

      return false;
   }
}
// The example displays the following output:
//        01 = 0.99999999999999989: True
Module Example
   Public Sub Main()
      Dim value1 As Double = .1 * 10
      Dim value2 As Double = 0
      For ctr As Integer =  0 To 9
         value2 += .1
      Next
               
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1))
   End Sub

   Public Function HasMinimalDifference(value1 As Double, value2 As Double, units As Integer) As Boolean
      Dim lValue1 As long =  BitConverter.DoubleToInt64Bits(value1)
      Dim lValue2 As long =  BitConverter.DoubleToInt64Bits(value2)
      
      ' If the signs are different, Return False except for +0 and -0.
      If ((lValue1 >> 63) <> (lValue2 >> 63)) Then
         If value1 = value2 Then
            Return True
         End If           
         Return False
      End If

      Dim diff As Long =  Math.Abs(lValue1 - lValue2)

      If diff <= units Then
         Return True
      End If

      Return False
   End Function
End Module
' The example displays the following output:
'       1 = 0.99999999999999989: True

超出所记录精度的浮点数的精度特定于 .NET Framework 的实现和版本。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,两个特定数字的比较可能会在 .NET Framework 的不同版本之间发生变化,因为数字的内部表示形式的精度可能会改变。Consequently, a comparison of two particular numbers might change between versions of the .NET Framework because the precision of the numbers' internal representation might change.

如果两 Double.NaN 值通过调用 Equals 方法进行相等测试,则该方法返回 trueIf two Double.NaN values are tested for equality by calling the Equals method, the method returns true. 但是,如果使用相等运算符测试两个 @no__t 值为相等的值,则运算符将返回 falseHowever, if two NaN values are tested for equality by using the equality operator, the operator returns false. 若要确定 @no__t 的值是否不是数字(NaN),另一种方法是调用 IsNaN 方法。When you want to determine whether the value of a Double is not a number (NaN), an alternative is to call the IsNaN method.

调用方说明

编译器重载决策可能会考虑两 Equals(Object) 方法重载的行为中的明显差异。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果定义了 @no__t 参数与 Double 之间的隐式转换,但该参数不是类型化为 Object,则编译器可能会执行隐式转换并调用 Equals(Double) 方法。If an implicit conversion between the obj argument and a Double is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Double) method. 否则,它们调用 Equals(Object) 方法,如果其 obj 参数不是 @no__t 值,则它将始终返回 falseOtherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Double value. 下面的示例演示两个方法重载之间的行为差异。The following example illustrates the difference in behavior between the two method overloads. 如果所有基元数值类型(Decimal 和中C#除外),则第一次比较将返回 true,因为编译器会自动执行扩大转换并调用 Equals(Double) 方法,而第二个比较返回 false因为编译器调用 @no__t 的方法。In the case of all primitive numeric types except for Decimal and in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Double) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2][!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2]

另请参阅

Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

public:
 override bool Equals(System::Object ^ obj);
public override bool Equals (object obj);
override this.Equals : obj -> bool
Public Overrides Function Equals (obj As Object) As Boolean

参数

obj
Object

与此实例进行比较的对象。An object to compare with this instance.

返回

如果 trueobj 的实例并且等于此实例的值,则为 Double;否则为 falsetrue if obj is an instance of Double and equals the value of this instance; otherwise, false.

注解

应慎用 @no__t 0 方法,因为两个值的精度不同,因此两个明显等效的值可能不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. 下面的示例报告 @no__t 值3333和除以3时返回的 @no__t 1 不相等。The following example reports that the Double value .3333 and the Double returned by dividing 1 by 3 are unequal.

// Initialize two doubles with apparently identical values
double double1 = .33333;
object double2 = 1/3;
// Compare them for equality
Console.WriteLine(double1.Equals(double2));    // displays false
' Initialize two doubles with apparently identical values
Dim double1 As Double = .33333
Dim double2 As Object = 1/3
' Compare them for equality
Console.WriteLine(double1.Equals(double2))    ' displays False

有关调用 Equals 方法的替代方法,请参阅 @no__t 重载的文档。For alternatives to calling the Equals method, see the documentation for the Equals(Double) overload.

备注

由于 Epsilon 定义其范围接近零的正值的最小表达式,因此两个相似值之间的差值幅度必须大于 EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference between two similar values must be greater than Epsilon. 通常情况下,它的数量大于 EpsilonTypically, it is many times greater than Epsilon.

超出所记录精度的浮点数的精度特定于 .NET Framework 的实现和版本。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,两个特定数字的比较可能会在 .NET Framework 的不同版本之间发生变化,因为数字的内部表示形式的精度可能会改变。Consequently, a comparison of two particular numbers might change between versions of the .NET Framework because the precision of the numbers' internal representation might change.

如果两 Double.NaN 值通过调用 Equals 方法进行相等测试,则该方法返回 trueIf two Double.NaN values are tested for equality by calling the Equals method, the method returns true. 但是,如果使用相等运算符测试两个 @no__t 值为相等的值,则运算符将返回 falseHowever, if two NaN values are tested for equality by using the equality operator, the operator returns false. 若要确定 @no__t 的值是否不是数字(NaN),另一种方法是调用 IsNaN 方法。When you want to determine whether the value of a Double is not a number (NaN), an alternative is to call the IsNaN method.

调用方说明

编译器重载决策可能会考虑两 Equals(Object) 方法重载的行为中的明显差异。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果定义了 @no__t 参数与 Double 之间的隐式转换,但该参数不是类型化为 Object,则编译器可能会执行隐式转换并调用 Equals(Double) 方法。If an implicit conversion between the obj argument and a Double is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Double) method. 否则,它们调用 Equals(Object) 方法,如果其 obj 参数不是 @no__t 值,则它将始终返回 falseOtherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Double value. 下面的示例演示两个方法重载之间的行为差异。The following example illustrates the difference in behavior between the two method overloads. 如果所有基元数值类型(Decimal 和中C#除外),则第一次比较将返回 true,因为编译器会自动执行扩大转换并调用 Equals(Double) 方法,而第二个比较返回 false因为编译器调用 @no__t 的方法。In the case of all primitive numeric types except for Decimal and in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Double) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2][!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2]

另请参阅

适用于