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)

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。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.

實作

備註

這個方法會實作用 System.IEquatable<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,且參數類型為 Int32For example, suppose the instance type is Double and the parameter type is Int32. Microsoft C#編譯器會產生指示,以 Double 物件的形式來表示參數的值,然後產生 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

Equals 方法應該謹慎使用,因為兩個明顯的相等值可能會因為兩個值的不同精確度而不相等。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. 下列範例會報告 Double 值333333和除以 1 x 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,上述程式碼範例發現的兩個 Double 值不相等。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. 通常,它會比 Epsilon多倍。Typically, 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. 不過,這會造成問題,因為可接受的差異邊界取決於 Double 值的大小。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,因為在使用值為零的 Double 時,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,這是前一個程式碼範例中,Equals(Double) 方法所找到的兩個 Double 值是不相等的。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. 不過,如果使用等號比較運算子來測試兩個 NaN 值是否相等,則運算子會傳回 falseHowever, if two NaN values are tested for equality by using the equality operator, the operator returns false. 當您想要判斷 Double 的值是否不是數位(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. 如果 obj 引數與 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 引數不是 Double 值,則一律會傳回 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,因為編譯器會呼叫 Equals(Object) 方法。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.web. Equals # 2][! code-vbsystem.web. Equals # 2][!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2]

另請參閱

Equals(Object)

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。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.

備註

Equals 方法應該謹慎使用,因為兩個明顯的相等值可能會因為兩個值的不同精確度而不相等。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. 下列範例會報告 Double 值3333和除以 1 x 3 所傳回的 Double 不相等。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 方法的替代方案,請參閱 Equals(Double) 多載的檔。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. 通常,它會比 Epsilon多倍。Typically, 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. 不過,如果使用等號比較運算子來測試兩個 NaN 值是否相等,則運算子會傳回 falseHowever, if two NaN values are tested for equality by using the equality operator, the operator returns false. 當您想要判斷 Double 的值是否不是數位(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. 如果 obj 引數與 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 引數不是 Double 值,則一律會傳回 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,因為編譯器會呼叫 Equals(Object) 方法。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.web. Equals # 2][! code-vbsystem.web. Equals # 2][!code-csharpSystem.Double.Equals#2] [!code-vbSystem.Double.Equals#2]

另請參閱

適用於